javascript:将数据发布到同一页面
问题描述:
$(document).ready(function(){
$('#list li').click(function(){
var ID= $(this).attr('id');
$.post("index.php", ID,
function(){
$("#category").html(ID);
}
);
});
});
此代码显示我在html <div id="category">
中选择的列表ID。javascript:将数据发布到同一页面
问题
有什么办法可以直接将数据发布到PHP代码并回显它吗?我需要php中的数据,因为我想在查询中使用它。
答
$.ajax({
type: "POST",
url: 'index.php',
data: { id: ID }, // name of the post variable ($_POST['id'])
success: function(data) {
console.log('successfully posted data! response body: ' + data);
}
});
答
也许你可以使用Ajax:
$('#list li').click(function(){
var ID = $(this).attr('id');
$.ajax(
url:"index.php", //Page with data
data:{id: ID},
type: "POST", //You can use any method POST, GET, DELETE, PUT...
success:function(result){
$("#category").html(result);
});
});
答
您还没有发送键/值对...只有一个值。
您还没有添加的参数在完成回调的响应
变化
$.post("index.php", ID, function(){
$("#category").html(ID);
});
要
$.post("index.php", {id: ID}, function(response){ //object used for key/value pairs
$("#category").html(response.data);
},'json')
.fail(function(error){
alert("Ooops ..something went wrong");
});
然后进行简单的PHP测试
echo json_encode(array('data'=>'The ID sent was '. $_POST['id']));
上午得到错误N otice:未定义的索引:编号 在这条线上我的代码: echo json_encode(array('data'=>'发送的ID是'。 $ _POST [ 'ID'])); – Darius92
你用对象和我展示的一样吗?在浏览器开发工具(F12)中,网络可以准确检查发送的内容。也可以执行'$ _POST'的转储,看看它在响应的开发工具中的请求体中看起来像什么或者将它记录到回调中的控制台上 – charlietfl
正在收到错误警报(“Ooops ..出错了”); (数组'('data'=>'发送的ID是'。$ _ POST ['id']));}我添加了if(isset($ _ POST ['id']))line echo before json_encode 它看起来像变量没有发布 – Darius92