2011-05-24 101 views
1

我想知道如何在我的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); 
      } 
     }); 

回答

2

這似乎是響應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

0

我通常使用以下方法來處理返回的JSON對象:

data = $.parseJSON(data); 

然後data.lastID應該回到你期待lastID值。