简体   繁体   中英

Getting json array from php

I know that you can get with getJSON the JSON array from PHP. But I cannot make it return the array so I can save it.

Is there a way to do this anyway?

For example if I made a function called getJSONInfo() and I want it to return the JSON array from PHP.

Example from answer of edwardmp:

$.getJSON("http://site.com/file.php?id=2", function(json){
    var newArray = json;
});

var username = newArray.username;

Sure there is a way:

In your JS/HTML page:

$.getJSON("http://site.com/file.php", function(json){
    alert("JSON Data: " + json);
});

In your PHP file:

$results = array("key" => "value");
echo $_GET['callback'] . '(' . json_encode($results) . ')';

If you supply a GET parameter, use it like this, not directly in the url.

var myparameter = 'parameter content';

$.getJSON('site.com/file.php', { myparameter: escape(myparameter) }, function(data) {
    // code here
});

It would appear you want this code to work asyncrhonously:

var newArray = $.ajax({
    async=true,
    dataType: "json",
    url: "http://site.com/file.php?id=2"
});

// this line will only be reached AFTER the HTTP request has completed
alert(newArray.username);

However (alternatively) I would really recommend handling all of the code that uses myArray.username in the callback anyway. That's just how AJAX is meant to work in the end, otherwise it's just JAX! That would look somewhat like this:

function haz_json(newArray) {
    alert(newArray.username);
}
$.ajax({
    dataType: "json",
    url: "http://site.com/file.php?id=2",
    success: haz_json
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM