问题描述
当通过ajax从jquery调用php时,有任何响应.我更改了dataType
并放置了json
而不是html
.我在想的问题是,因为ajax调用永远不会触发php代码,似乎$_POST['retriveForm']
从不带有值.
When call php from jquery via ajax ,have any response .I changed the dataType
and put json
instead html
.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm']
never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
和jQuery:
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
如果重要的话,代码都在同一页面上.
Code is all in the same page if that may be important.
推荐答案
由于AJAX代码位于同一脚本中,因此请确保在这种情况下不输出任何常规HTML.您的PHP代码应该在脚本的开始处,然后输出任何HTML.并且您应该在回显JSON之后退出脚本.否则,您的JSON将与HTML混合在一起,而jQuery将无法解析响应.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
此外,您没有在循环中正确添加到$data_json
.您每次都在覆盖变量,而不是将其压入该变量.
Also, you're not correctly adding to $data_json
in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
然后在success
函数中,您需要索引response
的元素,因为它是一个数组,而不是单个对象.
Then in the success
function, you'll need to index the elements of response
, since it's an array, not a single object.
这篇关于将值从JQUERY传递给PHP,并返回JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!