带有多个返回值的Javascript和PHP ajax调用返回undefined

问题描述:

I have the following code with which I'm trying to do an AJAX call that can return multiple values

    // Make an ajax call to insert a new row.
    // Newer jquery uses done and fail instead of success and error.
    $.post("add_row_item.php", {
      work_order_id: 1
    }).done(function(data) {
      // Ajax request was successful.
      console.log(data);
      // Check if database query produced errors.
      if(data.error != "") {
        alert('Error trying to add a row - ' + data.error);
      }
    }).fail(function(xhr, status, error) {
      // Ajax request failed.
      var errorMessage = xhr.status + ': ' + xhr.statusText;
      alert('Error trying to add a row - ' + errorMessage);
    });

The PHP code encodes the return message as follows:

echo json_encode(array("error" => "Error: " . mysqli_error($con)));

I get the following on the browser console:

{"error":"Error: Table 'db.tutorials' doesn't exist"}

But the alert gives me an undefined in the message:

Error trying to add a row - undefined

Anybody know where I'm going wrong with the alert part?

我有以下代码,我正在尝试进行 AJAX code>调用 可以返回多个值 p>

  //进行ajax调用以插入新行。
 //较新的jquery使用done和fail而不是成功和错误。
 $。  post(“add_row_item.php”,{
 work_order_id:1 
})。done(function(data){
 // Ajax请求成功。
 console.log(data); 
 //检查是否 数据库查询产生错误。
 if(data.error!=“”){
 alert('错误尝试添加行 - '+ data.error); 
} 
})。失败(函数(xhr)  ,状态,错误){
 // Ajax请求失败。
 var errorMessage = xhr.status +':'+ xhr.statusText; 
 alert('尝试添加行时出错 - '+ errorMessage); 
  }}; 
  code>  pre> 
 
 

PHP code>代码对返回消息进行编码,如下所示: p>

  echo json_encode(array(“error”=>“Error:”。mysqli_error($ con))); 
  code>  pre> 
 
  

我在浏览器控制台上获得以下内容: p>

  {“error”:“错误:表'db.tutorials'不存在”} 
  代码>  pre> 
 
 

但是警报在消息中给出了 undefined code>: p>

 尝试添加错误时出错 row  -  undefined 
  code>  pre> 
 
 

有人知道警报部分出了什么问题吗? p> div>

data is actually a string, '{"error":"Error: Table 'db.tutorials' doesn't exist"}'. You can convert it to an object using JSON.parse:

data = JSON.parse(data);

or alternatively, specify

dataType : "json"

to your ajax call and it will be automatically converted on receipt (see the manual).