php json_encode不给纯对象

时间:2016-03-07 21:47:58

标签: javascript php json

这可能是一个非常简单的问题,但现在正在努力解决这四个问题。

我有一个php文件:

procedure TForm1.Button1Click(Sender: TObject);
begin
  if (Edit1.Text = 'User') and (Edit2.Text = 'pass') then
    modalresult := System.UITypes.mrOK;
end;

现在我想给这个对象如下:

$array = array(
        "id"=> 1, "firstName"=> "James", "lastName"=> "King", "managerId"=> 0, "managerName"=> "", "title"=> "President and CEO", "department"=> "Corporate", "cellPhone"=> "617-000-0001", "officePhone"=> "781-000-0001", "email"=> "jking@fakemail.com", "city"=> "Boston, MA", "pic"=> "James_King.jpg", "twitterId"=> "@fakejking", "blog"=> "http://coenraets.org"
    );
echo json_encode($array);

现在我收到以下回复:

Object
blog: "http://coenraets.org"
cellPhone: "617-000-0001"
city: "Boston, MA"
department: "Corporate"
email: "jking@fakemail.com"
firstName: "James"
id: 1
lastName: "King"
managerId: 0
managerName: ""
officePhone: "781-000-0001"
pic: "James_King.jpg"
title: "President and CEO"
twitterId: "@fakejking"

我真的不知道在哪里看,我可能做错了但我真的不知道。

更新

JS

abort: (a)

always: ()

complete: ()

done: ()

error: ()

....

readyState: 4

responseText: "{"id":1,"firstName":"James","lastName":"King","managerId":0,"managerName":"","title":"President and CEO","department":"Corporate","cellPhone":"617-000-0001","officePhone":"781-000-0001","email":"jking@fakemail.com","city":"Boston, MA","pic":"James_King.jpg","twitterId":"@fakejking","blog":"http:\/\/coenraets.org"}"

setRequestHeader: (a,b)

state: ()

... 

__proto__: Object

行console.log(JSON.parse(result.responseText))给出了以下错误:

var result = $.ajax({
          url: "http://localhost/cordova/employees/index.php?name="+ searchKey,
          context: document.body
        });
    console.log(JSON.parse(result.responseText));

3 个答案:

答案 0 :(得分:3)

那是因为您正在查看XMLHttpRequest对象。您需要解析响应以获取对象。

var obj = JSON.parse(xhr.responseText);

其中xhr是您正在console.log开启的对象的名称。

答案 1 :(得分:0)

$.ajax()发出异步HTTP请求,因此您无法正确获取响应。你必须等待响应来找你。当您的响应准备就绪时,done()构造可用于触发回调。

var getEmployee = $.ajax({
    url: "http://localhost/cordova/employees/index.php?name="+ searchKey,
    context: document.body,
    dataType: 'json'
});
// the callback will get fired when the response is received
getEmployee.done(function (result) {
    console.log(result.blog);
});
// this will get fired immediately before the response is even received
console.log(getEmployee.responseText);  

答案 2 :(得分:0)

这是一个简单的功能。 阅读PHP中的stdClass 并将您的PHP代码修改为:

$array = new stdClass();
$array->id = 1;
$array->firstName = "James";
//..... other fields
echo json_encode($array);