我在 PHP AJAX 中做了类似的事情:
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
print json_encode($rows);
我的调用JavaScript代码是这样的:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
//$("input[type=button]").click(function()
{
var name = $("#problem_name").val();
var problem_blurb = $("#problem_blurb").val();
var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
if(name=='' || problem_blurb == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
如何将编码的 JSON 传输回 jQuery 调用、解码并输出该数据?我自己循环遍历数据并通过将字符串连接在一起来制作 JSON 代码会更好吗?
谢谢!!
最佳答案
设置dataType:'json'
这样你就不需要解析json
$.ajax({
type: "POST",
dataType:'json', <----
url: "/problems/add_problem.php", <---- here you call the php file
data: dataString,
success: function(data) <--- here the data sent by php is receieved
{
// data will contain the decoded json sent by server
// you can do data.property that depends upon how the json is structured
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
add_problem.php
$name=$_POST['problem_name']; // get the name here
$desc=$_POST['problem_blurb']; //get the description here
$rows = array();
//fetch data from DB
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
print json_encode($rows); //json encode it and send back to ajax success handler
//or
//echo json_encode($rows);
关于php - 如何将编码的 JSON 字符串返回给 jQuery 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7535189/