1

I've been stuck on this for days now...the problem is this: I want to get multiple values from a PHP file through jQuery Ajax Json. but as soon as i add the dataType: 'json', to it, that's the end of things. I am using the given code:


PHP - check.php

$oid=1;
$f=10;
echo json_encode(array("oid" => $oid, "cid" => $f)); 

PS: THE ABOVE CODE IS INSIDE A LOOP THAT RETURNS MANY oid's AND cid's AT ONE TIME!

I've not included the part above or below the script cause it can compromise the security of my site.. :P but this in a nutshell is what the script does.

and here goes the javascript:


jQuery - scripts.js

$.ajax({
    type: "POST",
    dataType: 'json',
    url: "check.php",
    data: {anu:"bhav"}
}).done(function( result ) {
    if(result!='0'){
        var res=result.oid[0];
        alert(res);
    }
});
4

3 回答 3

2

If it is inside a loop, you need to build an array with all your arrays in it.

for ($i=0; $i<count($array); $i++) {
    $oid=1;
    $f=10;
    $results[] = array("oid" => $oid, "cid" => $f));
}

echo json_encode($results);
于 2013-08-04T13:25:49.160 回答
1

Add below code before echo json_encode(array("oid" => $oid, "cid" => $f));

header('Content-type: application/json');

Change below line

var res = result.oid[0];

As below and try:

var res = result.oid;
于 2013-08-04T11:55:46.410 回答
1

You wrote:

PS: THE ABOVE CODE IS INSIDE A LOOP THAT RETURNS MANY oid's AND cid's AT ONE TIME!

That one line of information is almost certain to be the ultimate cause of your problem.

Echoing multiple blocks of JSON one after the other does not result in one large block of valid JSON.

It results in a string that may look like JSON but is not valid, and will not produce any data if you pass it through a JSON parser.

Your PHP program should print one, and only one JSON block, generated by a single call to json_encode().

You can do this by copying the data into an array inside your loop, rather than echoing it there, and then doing your json_encode()` call on that big array, rather than the individual blocks of data.

Hope that helps explain things.

于 2013-08-04T14:19:06.607 回答