将 json_encode 与 jquery.ajax() 一起使用时如何返回特定值?

发布于 2024-11-08 23:02:16 字数 1882 浏览 0 评论 0原文

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

我的 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);
            }
        });

I'm wondering how to reference specific variables in my jquery.ajax() success function.

My php code on addit.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);
  }

My jQuery code:

        $.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);
            }
        });

Returns in the alert:

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

How can I now reference that in the success function? I was trying something like this, but it didn't work (returns "undefined" in the alert):

        $.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);
            }
        });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌能量女王 2024-11-15 23:02:16

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

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

  2. 更新您的 PHP 以使用正确的内容类型进行响应 header('Content-type: application/json'); - 这将允许 jQuery 自动找出响应是 JSON,并且它将为您解析它,而不需要 dataType 值。这也将使其他使用者更容易,因为您将显式指定数据类型。

It seems like the response JSON isn't being parsed into an object, which is why the alert() displays the entire string (otherwise you'd see [object Object]). You could parse it on your own but a better solution might be to do one (or both) of the following:

  1. Add dataType = "json" to the call to ajax() to tell jQuery that you're expecting JSON as the response; jQuery will then parse the result and give you a data object that you can work with and not just a string. Also, note that alert() only accepts one argument, all subsequent ones will simply be ignored.

  2. Update your PHP to respond with the correct content type header('Content-type: application/json'); - this will allow jQuery to automagically figure out that the response is JSON and it will parse it for you, without needing a dataType value. This will also make it easier for other consumers since you'll be explicitly specifying the data type.

吲‖鸣 2024-11-15 23:02:16

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

data = $.parseJSON(data);

然后 data.lastID 应该返回您期望的 lastID 值。

I usually use the following to process the returned json object:

data = $.parseJSON(data);

Then data.lastID should return the value you expect for lastID.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文