我需要将此表单发布到数据库并检索新添加的信息,而无需使用XHR进行刷新。
页面加载了一些可以编辑的初始元素,并且可以通过按按钮动态添加更多的"新"元素(新用户需要这样做,因为他们没有预先存在的任务)。它通过session_id)跟踪你是谁。
我已经做了13个小时了,有点累了。
代码:index . php
<?php
//Sets unique session for the current visitor and keeps track of information for use with database
$time = time();
$date = $today = date("Ymd");
$id = $time + $date;
$id = session_id();
if(empty($id)) session_start();
//echo "SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<title>Simple To-Do List</title>
<?php
// Create connection via my connect.php file
require 'connect.php';
// Create query
$query= "select * from checklist where SID = '".session_id()."'";
$result = mysql_query($query);
// Create requisite array for checklist
$checklistItems = array();
//Check to ensure query won't implode and is valid
if($result === FALSE) {
die(mysql_error());
}
// Calculates number of rows from query
$num=mysql_numrows($result);
mysql_close($con);
?>
<!-- javascript code to dynamically add new form fields as well as check'uncheck all boxes -->
<script src="//code.jquery.com/jquery-latest.min.js" language="javascript" type="text/javascript"></script>
<script src="addInput.js" language="Javascript" type="text/javascript"></script>
</head>
<body>
<h1>My To-Dos</h1>
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type='"text'" value='"$entry'" name='"textfield$CID;'" id='"textfield$CID;'" onchange='"showUser(this.value)'" />";
echo "<input type='"checkbox'" name='"checkbox$CID;'" id='"checkbox$CID;'" value='"$checked'"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
</body>
</html>
connect.php
<?php
// Create connection
$con=mysql_connect("localhost","root","");
$selected = mysql_select_db("madmonk",$con);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
?>
addInput.js
// Creates new dynamic elements within HTML body
var counter = 0;
var limit = 8;
function addInput(divName){
i=counter; i++;
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <input type='text'name='myInputs["+i+"]'><input type='checkbox' name='myInputs["+i+"]'><br>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
//Checks'unchecks all checkboxes on the web page
function checkAll(formname, checktoggle)
{
var checkboxes = new Array();
checkboxes = document[formname].getElementsByTagName('input');
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = checktoggle;
}
}
}
//AJAX code to communicate with server without page refresh
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'processor.php',
data: $('#checklist').serialize(),
dataType: 'html',
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//success callback function
alert (success);
},
error: function() {
//error callback function
alert (failure);
}
});
});
我知道一个事实,我有问题与上面的AJAX代码。这很关键,我不能让它工作。我以前从来没有尝试过这样的事情,我决定试着把我的心思放在这件事上,把它完成。啊。
processor.php
<?php
require 'connect.php';
$entry = $_POST['entry'];
$checked = $_POST['checked'];
$num_items = count($entry);
for ($i = 0; $i < $num_items; $i++)
{
$sql="INSERT INTO checklist (Entry, Checked, SID)
VALUES ($checked, $entry, session_id()) WHERE SID = '".session_id()."'";}
mysql_close($con);
?>
^这是粗糙的,完全未完成。
我如何与动态字段交互并通过它们循环到管道通过mysql和php进入数据库?
我如何得到它更新的index.php页面的新值新项目的无缝添加?
我怎么能得到AJAX的工作?
为了我的缘故,请非常具体。我是AJAX的新手
$('checklistSubmit')
应为$('#checklistSubmit')
。您需要#
来查找ID。
此外,点击处理程序绑定应该在$(function() { ... });
中,以便它不会运行,直到表单加载到DOM中。
你的成功函数包含$('div.successmessage').html(data);
,但我没有看到DIV类在你的PHP。
$(e).stopPropagation();
应:e.stopPropagation();
由于e
不是一个DOM元素,它是一个事件。
1)与动态字段交互,只需给它们一个类,如class="dynamicField"
和myId = <whatever the id you care about is>
或其他,然后添加
$(".dynamicField").change(function(){
$.post("updateDB.php",
{
"dataToGoInDB": $(this).val(),
"idYouCareAbout": $(this).attr("myId")
},
function(data){
console.log(data.responseBackFromDB);
}, "json");
});
,然后有一个php页面updateDB.php
,将查看POST变量,正确地清理它们以避免SQL注入,然后做任何你需要做的DB。
如果您计划在创建DOM之后添加动态字段,请这样做:
$("document").on("change", ".dynamicField", function(){
$.post("updateDB.php",
{
"dataToGoInDB": $(this).val(),
"idYouCareAbout": $(this).attr("myId")
},
function(data){
console.log(data.responseBackFromDB);
}, "json");
});
将为您将.change附加到. dynamicfield的任何新实例。(http://api.jquery.com/on/)
2)要添加新字段,尝试使用jQuery DOM操作方法之一,如append http://api.jquery.com/append/看看我是怎么回答#1的
希望对你有帮助。
use this…$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
查看此链接http://api.jquery.com/jQuery.post/
您可以采用以下方法来处理ajax:-
- 将ajax调用放入函数中。说initAjax()。
- 将点击或更改处理程序放在initMyForm()等函数中
-
加载文件时执行此函数
$(document).ready(function(){ initAjax(); initMyForm(); }
-
在ajax调用的成功或失败回调中更新表单的HTML,然后再次调用initMyForm();
示例代码 function initAjax(){ $.ajax({ url : 'myurl', success : function(data){ playWithData(data); }, failure : function(data){ } }); } function playWithData(data){ //after playing with data initMyForm(); } function initMyForm(){ }
console.log和google chrome的开发者工具(按F12)也是好朋友。您还可以为XHR请求设置断点。