开发者

call jQuery JSON function and pass back resulting payload

I would like to call jQuery JSON function and pass back results as JSON object (Javascript array?), but I am not quite understanding dynamics of what is happening here.

myJSON = myFunction(productNo)开发者_开发知识库
$.each(myJSON, function(i,user){
   alert (user.description)
}


function myFunction(productNo)
{
  $.getJSON
  (
      "processors/process_1.php",
       { productNo: 'ABC' },                
       function(data)
       {        
           return data;
       }
   )        
}


Ajax is asynchronous, so you cannot return something from the callback - it will not complete until after your calling function has exited. Instead you need to do all your work in the callback. You should use a closure to pass along the work you want to be done when the ajax call completes:

myFunction(productNo, function(myJSON) {
    $.each(myJSON, function(i,user){
       alert (user.description)
    }
});


function myFunction(productNo, onComplete)
{
  $.getJSON
  (
      "processors/process_1.php",
       { productNo: 'ABC' },                
       onComplete
   )        
}


What you're getting back is a native Javascript data structure (JSON stands for Javascript Object Notation. I'm not sure I understand your question either... are you asking what is happening here?

What you're doing right now is iterating over the properties of the data object you got back (which is in the JSON format). Are you expecting a list of user objects of some kind? Each one having a description attribute?

EDIT

Ok, so after reading your comment I think I've figured out your problem - since AJAX is asynchronous, you can only work on the data once the request has completed. That's why you're getting back undefined, because the browser continues executing the code without waiting for the request to complete. What you need to do here is work with the data in your callback:

function myFunction(productNo)
{
  $.getJSON(
      "processors/process_1.php",
       { productNo: 'ABC' },                
       function(data) {
           $.each(data, function(i, user){
                 alert (user.description)
           }
       }
   )        
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜