php - 如何将编码的 JSON 字符串返回给 jQuery 调用?

标签 php javascript jquery json

我在 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/

相关文章:

javascript - 如何使用更改方法更改 DropDownList 的选定值?

php - 计算关联数组中的唯一值

php - Laravel home(~) SCSS 路径无法正确解析

php - 从准备好的语句中获取文本(PHP、PDO)

php - MYSQL 按记录分组

javascript - 使用数组方法时在哪里使用附加条件

javascript - 我怎样才能用类似的事件简化这个 Javascript

jQuery SlideUp 在 iOS 上闪烁

javascript - 无法在我的贪吃蛇游戏中动态显示分数

javascript - Sequelize连接错误