overriding default property in an object
i want to make an ajax call to a php file that return a users info in json then take that data and put it in an object property
example:
System = {
prop1= ''
}
i just want to override the prop1 property
im 开发者_JAVA技巧using jquery to make the ajax call
The easiest way to set up JSON output in PHP is to simply use a stdClass() object and call json_encode() on it.
$obj = new stdClass();
$obj->name = 'user name';
$obj->prop1 = 'property 1';
echo json_encode($obj);
After you receive this from the Ajax call, you'll have a javascript object with a name
and a prop1
property.
If you want to replace an existing object's properties with the ones you fetched from your Ajax call, you'll have to do it manually, ie. check the JSON result for the property you want, and set it on your existing object. The way around that would be to only output the properties you want in your JSON, and just use them all by iterating over the fetched ajax object. Example:
for(prop in fetchedAjaxObject) {
existingObject.prop = x.prop;
}
EDIT
In response to your comment below, it sounds like you just want to get the JSON object from the result of a JQuery call?
In that case you just set up a handler function for the "success" property of the ajax call. The result automatically gets passed to the handler function. There's examples in the JQuery docs, but here's a basic one:
$.ajax({
url: 'www.example.com',
success: function(data) {
//data is your JSON object
yourObject.prop = data.prop1;
}
});
精彩评论