PHP (processing.php):
$responce["x"] = 0;
$responce["y"] = [1, 3];
echo json_encode($responce);
javascript:
$.get("processing.php", function(data){
alert("Data: " + data)
});
Output (alert):
Data: {"x":0,"y":["1","3"]}
I need to access the variable x, and the array y in javascript ?!!
Parse the JSON string with $.parseJSON()
.
Then, access data.x
.
$.get("processing.php", function(data){
data = $.parseJSON(data);
var x = data.x;
});
Alternatively, you can set the dataType
to json
or use $.getJSON()
which will automatically do it.
According to your response Data: {"x":0,"y":["1","3"]}
$.get("processing.php", function(data){
alert(data.x); // Will alert "0"
alert(data.y[0]); // Will alert "1"
alert(data.y[1]); // Will alert "3"
}, "json");
With the jQuery.ajax Method you have the possibility to set the dataType
attribute to json
. Then you can have a function success: function ( data ) { alert (data.x + data.y); }
success: function ( data ) { alert (data.x + data.y); }
. For more infos look at the documentation at your own.
Edit: jQuery.getJSON () is what you are looking for... it is like the jQuery.get
method but parses the result to a javascript object.
Your code would than look like this:
$.getJSON("processing.php", function(data){
var x = data.x;
var y = data.y;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.