Вопрос

I have a login using getJSON and PHP.

Right now all it does it checks if the user and password is valid but if it is I want to pass further information to the client.

Right now on the server side I do this:

if ($result->num_rows) {            
    echo '{"response":{"error": "1"}}';         
} else {
    echo '{"response":{"error": "0"}}';
}

and on the client side I have this:

if (json.response.error == "1") {
    data = "Welcome "+username;
    alert(data);
} else {
    // Login fail
    data = "Wrong Username/Password";
    alert(data);
}

So basically it's just checking.

How can I pass some more information from the server to the client?

Update: I've changed the code to this but it's now not working:

Server:

if ($result->num_rows) {

//echo '{"response":{"error": "1"}}';
$data = array(
'response'     => array(
'error'    => 1,
),
'someData'     => 'data';
);
print json_encode($data);
}

Client:

$.getJSON("server.php", {username:username,password:password},function(data)
{

alert('hello');
var json = JSON.parse(data);
alert(json.responseCode);


});
Это было полезно?

Решение

On the server side, You can create an array containing all the data you need and then send it from the server to the client using json_encode() :

$data = array(
    'response'     => array(
        'error'    => 1,
    ),
    'someData'     => 'data',
    ...
);
print json_encode($data);

And on the client side :

var json = JSON.parse(data);
alert(json.response.error);

Hope it helps !

Другие советы

You have to use jQuery.parseJSON(json) where json here is a well formed json string.

From the documentation:

It takes a well-formed JSON string and returns the resulting JavaScript object.

So you have to parse the string first to a javascript object.

var json = $.parseJSON(data); // data is the json string
if (json.response.error == "1") {
   data = "Welcome "+username;
   alert(data);
} else {
   // Login fail
   data = "Wrong Username/Password";
   alert(data);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top