Some information - I'm creating an autoplete which gets the data from a json feed. The JSON part works fine and the result is valid.
When I'm obtaining it, I'm using json2.js and running JSON.parse. When I try and output it tells me that it (the object containing the parsed JSON text) is actually undefined.
If I run an alert on the object and then output it works. It's probably something quite simple. But this is the bit that is confusing as it works fine if I alert the object
I know that it won't work on everything, I'm just trying to get it working for now and I'll improve it.
Thank you and if there is any more information I can provide I will.
The code
//sURL takes a search term that's passed into the function
var JSON_object = {};
var oRequest = new XMLHttpRequest();
var sURL = "datalinkhere"+input.value;
oRequest.open("GET",sURL,true);
oRequest.setRequestHeader("User-Agent",navigator.userAgent);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4 && oRequest.status == 200)
{
JSON_object = JSON.parse( oRequest.responseText );
}
};
oRequest.send(null);
suggestion(JSON_object,input);
function suggestion(inp,targetid)
{
document.getElementById('autosuggest').style.display='block';
document.getElementById('autosuggest').innerHTML=inp[1].namefield;
}
Some information - I'm creating an autoplete which gets the data from a json feed. The JSON part works fine and the result is valid.
When I'm obtaining it, I'm using json2.js and running JSON.parse. When I try and output it tells me that it (the object containing the parsed JSON text) is actually undefined.
If I run an alert on the object and then output it works. It's probably something quite simple. But this is the bit that is confusing as it works fine if I alert the object
I know that it won't work on everything, I'm just trying to get it working for now and I'll improve it.
Thank you and if there is any more information I can provide I will.
The code
//sURL takes a search term that's passed into the function
var JSON_object = {};
var oRequest = new XMLHttpRequest();
var sURL = "datalinkhere"+input.value;
oRequest.open("GET",sURL,true);
oRequest.setRequestHeader("User-Agent",navigator.userAgent);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4 && oRequest.status == 200)
{
JSON_object = JSON.parse( oRequest.responseText );
}
};
oRequest.send(null);
suggestion(JSON_object,input);
function suggestion(inp,targetid)
{
document.getElementById('autosuggest').style.display='block';
document.getElementById('autosuggest').innerHTML=inp[1].namefield;
}
Share
Improve this question
edited Sep 8, 2010 at 10:44
BoltClock
725k165 gold badges1.4k silver badges1.4k bronze badges
asked Sep 8, 2010 at 10:44
PaulPaul
1,1221 gold badge10 silver badges18 bronze badges
1
- By the way the status could be not only 200. The value 304 (Not Modified) could be retured for example if the data will be get from the local cache and the server conferm that the data are not changed (see 10.3.5 of ietf/rfc/rfc2616). – Oleg Commented Sep 8, 2010 at 11:11
4 Answers
Reset to default 2The problem ist not alerting the json or not it's the concept of your code. Ajax requests work asynchronously, thus your oRequest.send call will not block until the data has been loaded, the data is loaded in the background.
So you can have luck and the data is available when the next line (suggestion-call) and your code works or you will get an undefined var.
You'll have to write your code asynchronously: Put the suggestion-call direcly after the JSON.parse-call and all will work like a charm.
You might be interested in the function that jQuery uses:
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the ining data is actual JSON
// Logic borrowed from http://json/json2.js
if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} else {
jQuery.error( "Invalid JSON: " + data );
}
}
There are a couple of jQuery methods in there, namely trim and error, you can find out what they are by reading the source: http://code.jquery./jquery-1.4.2.js
The interesting part is this bit:
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
It's a neat way of reading the JSON without using eval - setting up a function that returns the data.
Try JSON_object = eval(oRequest.responseText);
The best JavaScript to do it is JSON.parse
function from json2.js which you can download from http://www.json/js.html. It is the most official version of JSON.parse
and JSON.stringify
. By the way the implementation will check whether the web browser has internal implementation of these functions and uses them if they exist.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745393114a4625754.html
评论列表(0条)