Problem to retrieve JSON after AJAX call
I have made an AJAX function with jQuery. The function works properly, and server return a JSON, but I can't use it in m开发者_JAVA技巧y JS script
Server side :
$array = array();
$array["count"] = count($accounts_list)."";
for($i=0; $i<count($accounts_list); $i++)
{
$account = $accounts_list[$i];
$array["marker"]["name"] = $account->name;
$array["marker"]["lat"] = $account->map_latitude;
$array["marker"]["lon"] = $account->map_longitude;
}
echo json_encode($array);
Client side :
$.ajax({
type: "POST",
url: "index.php?module=cap_Maps&action=AddMarkers",
data: dataString,
dataType: "json",
success: function(data) {
if (data == "error"){
$(".tr_legend").before("<tr><td colspan='2' id='error'><span class='error_maps'>Erreur lors du chargement des marqueurs</span><td><tr>");
}
else {
alert(data);
var obj = jQuery.parseJSON( data )
alert (obj.count);
}
}
});
JSON returns by server:
{"count":"371","marker":{"name":"WAMPFLER","lat":"49.02751610","lon":"2.10611230"}}
Function alert(data)
returns my JSON, but if I try to parse it with jQuery.parseJSON( data )
, It doesn't work and alert(obj.count);
doesn't open.
EDIT
I have add error function:
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
},
And error occured :
XMLHttpRequest={"count":"358"}
textStatus=parsererror
errorThrown=Invalid JSON: {"count":"358"}
EDIT
If I had contentType: "application/json",
in my AJAX, I can return a static string which is considered as json, but if I try to execute other php code on my server, AJAX returns an 500 Internal server error
Try this :
var json = jQuery.parseJSON('{"count":"371","marker":{"name":"WAMPFLER","lat":"49.02751610","lon":"2.10611230"}}');
alert(json.count);
maybe you forget to give a string ' ' to parseJSON.
From jQuery.ajax
:
The
json
type parses the fetched data file as a JavaScript object and returns the constructed object as the result data.
So you don't need jQuery.parseJSON
, as the returned string already is parsed.
instead of using parseJson can you try just using eval.
$.ajax({
type: "POST",
url: "index.php?module=cap_Maps&action=AddMarkers",
data: dataString,
dataType: "text",
success: function(data) {
if (data == "error"){
$(".tr_legend").before("<tr><td colspan='2' id='error'><span class='error_maps'>Erreur lors du chargement des marqueurs</span><td><tr>");
}
else {
alert(data);
var obj = eval(data);
alert (obj.count);
}
}
});
HTH.
It looks like you are not sending the JSON with proper format from your server try to use json_encode() function.
The output buffer didn't empty so AJAX received buffer content + JSON so it wasn't a valid JSON.
I use ob_clean()
on server side just before output my JSON and it solves the problem.
精彩评论