开发者

jQuery ajax and passing returned data

开发者 https://www.devze.com 2023-02-14 23:21 出处:网络
I have the following piece of code. It all works but I\'m having a problem passing the data of the request to another variable.

I have the following piece of code.

It all works but I'm having a problem passing the data of the request to another variable.

At alert(items); it has the required data but I can't get it to be passed to alert(personen);

I know it has something to do with that because of the request the necessary data isn't available at the moment the alert(personen); is executed but I don't know how I can fix this in a decent way.

function getItems(type){
    var items;
    $.post('url' + type + '_ophalen', {},
    function(data){ 
        items = jQuery.parseJSON(data);
    });

    $(this).ajaxComplete(function() {
  开发者_JS百科  alert(items);
        return items;
    });
}


var personen = getItems('persoon');
alert(personen);


The problem

This is the problem:

var personen = getItems('persoon');
alert(personen);

your function getItems() has asynchronous functionality inside which means that it executes this way:

  1. you call it
  2. it then asynchronously posts something and continues with execution (not waiting for results)
  3. it sets an ajaxComplete functionality and continues execution
  4. it returns.

So basically the function doesn't return anything because it completes execution before internal asynchronous calls are complete. And it doesn't have any return statement to return anything.

That's why it also explains the behaviour that your first alert displays nothing and the second one displays your items. Even though you may have thought that data should be displayed first and the empty one (after the function has completed execution) later. Which could be buffling you as well.

function() {
    alert(items);
    return items;
}

The return items; is the return of the anonymous function displayed here, not the return of the getItems() function as you may have thought.

Unrecommended solution - synchronous calls

In your case if you wanted to return data from your getItems() function you should use synchronous calls. But you can only do that by using $.ajax() because it supports async: false.

Recommended solution

Although sync calls can be done I recommend you rather use asynchronous calls. Things can be done differently but will provide a much better experience if you used async calls. Ajax applications are better off when they're event-driven and not procedural what you're trying to do here.

If you need data to be available outside of your function you can always define a closure variable (may just as well be global, but that's usually not a good idea) that will be available outside of your function.

// creating a closure
(function(){

    // closure-global variable
    var personen = {
        data: null,
        available: false;
    };

    function getItems(type){
        $.post('url' + type + '_ophalen', {}, function(data) { 
            personen.data = jQuery.parseJSON(data);
            personen.available = true;
        });
    }

    getItems('persoon');

    // do other stuff in event-driven way
    // like when a user clicks something

    $("#SomeButtonOrLink").click(function(e){
        e.preventDefault();
        if (personen.available)
        {
            // do some processing
        }
        else
        {
            alert("Data not laoded.");
        }
    });
})();

So basically this code will be event driven. I don't know when the item loading should happen, but it should as well be related to some event (may be page load or user doing something). So everything is driven by events. Loading of items (if we say they should load on page load) and when that's done you don't have to process anything until user does something (in upper scenario it's a click event of some button or link). That's event driven execution.


I you want to see if the data is there or not, you should do it in your $.post callback function.

$.post('url' + type + '_ophalen', {},
    function(data){ // callback func
        items = jQuery.parseJSON(data);
        console.log(items);
        alert(items); // use both to see the power of console.log() ;)
    });

for jQuery < v1.5 you could also use $.ajax() $.post() is just a wraped version of $.ajax()...

$.ajax({
     type: 'POST',
     url: 'url' + type + '_ophalen',
     data: {} // no data to send ? Then why POST method instead of GET ?
     success: function(response) {
         // code for response....
         items = jQuery.parseJSON(response);
         console.log(items);
         alert(items); // use both to see the power of console.log() ;)
     }
});

P.S. I think you don't have to use $.parseJSON if the server sent only JSON (as string) with pain/text or `application/json

0

精彩评论

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