jQuery JSON Parsing Error
I have a web page that returns this JSON when called:
[{"id":"53","desc":"Roberts"}]
I am using this jQuery to call it by AJAX:
$.ajax ({
url: rootPath + "data/topology/stations",
dataType: 'json',
data: { areaID: $("#lbxArea").val () },
success: function (data) {
// Use data for actions
},
error: function (jqXHR, textStatus, errorThrown) {
alert (textStatus);
alert (errorThrown);
}
});
I used Firebug to confirm that the data being returned is what I put on top. Despite that, I fall into the error
callback and first see parsererror
in an alert box, and then I see
SyntaxError: JSON.parse: expected property name or '}'
I tried having the service return
{"list":[{"id":"53","desc":"Roberts"}]}
but that didn't change anything.
Whats the response content-type?! Try testing this response using this:
Getting the response content-type from jQuery.Post
also try not having the dataType: 'json' and check the return!
Well , I've spent some time on this question, but I'll make something that will serve those who have this problem.
The mistake is in wanting a property accesder response coming from PHP, introducing the following message:
*SyntaxError: JSON. parse: expected property name or '}'*
What you should do is convert JSON response to this is to use the function JSON.parse (data); inside we pass the response variable "data". I will comment a bit the code for better understanding:
success: function (data) {/ / on success ..
var json = JSON.parse (data);/ / Convert the JSON format input
console.log (JSON.parse (data));/ / explore the answer
alert ("" + json.msj);/ / Variable Access Testing with alert
....
Everything seems fine up here, however is dimensioned present the error, then that is because the way it is performing the response from PHP.
Here is a practical way to do it right:
We use json_encode function to return the data in JSON format, within the function passed an associative array with the variables that are required, Example:
echo json_encode (array ('success' => true, 'msg' => 'Hello registered user!'));
After these variables acquire client side without any problem, and simply, here a nitrous-code:
$. ajax ({/ / create an AJAX call ...
data: $ (this). serialize (), / / get the form data
type: $ (this). attr ('method'), / / GET or POST
url: $ (this). attr ('action'), / / the file to call
cache: false,
success: function (data) {/ / on success ..
var json = JSON.parse (data);
$ ('# created'). html (json.msj) / / update the DIV
I hope will be helpful ... any questions feel free to ask ...
You can install a Firefox add-on "JSONView". Maybe this gives you more information about the JSON string.
If you don't see anything (special JSON markup), you probaby miss a JSON header.
Edit: Firebug 1.4+ should show a JSON tab at a request.
链接地址: http://www.djcxy.com/p/46098.html上一篇: ajax被发送,但回调函数被忽略
下一篇: jQuery JSON解析错误