开发者

How can I return specific values when using json_encode with jquery.ajax()?

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_repl开发者_StackOverflow社区ace("/[^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);
            }
        });


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜