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

问题描述:

我想知道如何在我的jquery.ajax()成功函数中引用特定的变量。在addit.php如何使用jquery.ajax()使用json_encode时返回特定值?

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

这似乎是响应JSON没有被解析成一个对象,这就是为什么alert()显示整个字符串(否则你会看到[object Object])。你可以分析它自己,但更好的解决方案可能会做下列之一(或两者):

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

  2. 更新你的PHP与正确的内容类型header('Content-type: application/json');回应 - 这将让jQuery来自动地找出响应是JSON,它会分析它适合你,而无需dataType值。这将使其他消费者更容易,因为您将显式指定数据类型。

+0

太棒了!得到它的工作。谢谢..警报只是为了调试。我实际上使用这两个变量来构造一个URL来重定向用户,并且它完美地工作。再次感谢。 – 2011-05-24 01:55:06

+0

@bob_cobb太棒了,很高兴能有帮助:) – 2011-05-24 01:56:21

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

data = $.parseJSON(data); 

然后data.lastID应该回到你期待lastID值。