【问题标题】:How can I return specific values when using json_encode with jquery.ajax()?将 json_encode 与 jquery.ajax() 一起使用时如何返回特定值?
【发布时间】:2011-05-24 01:29:49
【问题描述】:

我想知道如何在我的 jquery.ajax() 成功函数中引用特定变量。

我在 addit.php 上的 php 代码

if ($_POST) {
    $user_id = $_SESSION['user_id'];
    $filename = $_SESSION['filename'];
    $quote = $_POST['quote'];

    $query = "INSERT INTO  `submissions` (
         `id` ,
         `user_id`,
        `quote` ,
        `filename` ,
        `date_added` ,
        `uploaded_ip`
        )
    VALUES (
    NULL , '{$user_id}',  '{$quote}',  '{$filename}',  NOW(), '{$_SERVER['REMOTE_ADDR']}')
    ";

    $db = DbConnector::getInstance();
    $db->insert($query);

    // remove funky characters from the quote
    $cleanRemove = preg_replace("/[^a-zA-Z0-9\s]/", "", $quote);

    // replace any whitespace with hyphens
    $cleanQuote = str_ireplace(" ", "-", $cleanRemove);

    // get the id of the last row inserted for the url
    $lastInsertId = mysql_insert_id();

  $returnUrl = array ("lastId"=>$lastInsertId, "cleanQuote"=>$cleanQuote);
  echo json_encode($returnUrl);
  }

我的 jQuery 代码:

        $.ajax({
            type: "POST",
            url: "addit.php",
            data: ({
                // this variable is declared above this function and passes in fine
                quote: quote
            }),
            success: function(msg){
                alert(msg);
            }
        });

在警报中返回:

{"lastId":91,"cleanQuote":"quote-test-for-stack-overflow"}

我现在如何在成功函数中引用它?我正在尝试这样的事情,但它不起作用(在警报中返回“未定义”):

        $.ajax({
            type: "POST",
            url: "addit.php",
            data: ({
                // this variable is declared above this function and passes in fine
                quote: quote
            }),
            success: function(data){
                alert(data.lastId,data.cleanQuote);
            }
        });

【问题讨论】:

    标签: php jquery ajax json


    【解决方案1】:

    似乎响应 JSON 没有被解析为对象,这就是 alert() 显示整个字符串的原因(否则您会看到 [object Object])。您可以自己解析它,但更好的解决方案可能是执行以下一项(或两项):

    1. dataType = "json" 添加到对ajax() 的调用中,以告诉jQuery 您期望JSON 作为响应;然后,jQuery 将解析结果并为您提供一个您可以使用的 data 对象,而不仅仅是一个字符串。另外,请注意alert() 只接受一个参数,所有后续参数都将被忽略。

    2. 1234563这也将使其他消费者更容易,因为您将明确指定数据类型。

    【讨论】:

    • 太棒了!得到它的工作。谢谢..警报只是为了调试。我实际上使用这两个变量来构造一个 URL 以将用户重定向到,并且它工作得很好。再次感谢。
    • @bob_cobb 太好了,很高兴能帮上忙 :)
    【解决方案2】:

    我通常使用以下方式来处理返回的json对象:

    data = $.parseJSON(data);
    

    那么 data.lastID 应该返回你期望的 lastID 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-19
      • 2013-07-20
      • 2019-04-23
      • 2022-01-01
      • 2013-05-12
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多