开发者

How to get data out of JQuery.post function

开发者 https://www.devze.com 2023-03-25 22:45 出处:网络
I\'m kind of new at JS but I can\'t believe I\'ve been unable to figure this out... myerr is defined globally.

I'm kind of new at JS but I can't believe I've been unable to figure this out...

myerr is defined globally. I set myerr=to the returned value from the post. Once I get outside the function it looses it's value.

myerr="";
$.post("/rpc/validate_song_entry", {'title':$('#title').val()}, function(data){
  alert(data.title); //----> Alerts e开发者_如何学Cxpected result.
  myerr=data.title;
  alert(myerr); //-----> Alerts expected result.
}, "json");
alert(myerr); //-------> Nothing. Blank dialog.

It seems to me it's a variable scope issue but I can't see how...

Edit: I posted this below but don't know how to delete it... I now understand that the post is done asynchronously. This makes sense. What does not make sense is that the alerts pop up in the order you see. I would expect the last alert (blank one) to appear first. It does not. It appears last.

I would expect the alerts inside the post function to appear last. Can anyone explain this?


you neesd to use jQuery.ajax and you need to set async :false

because your $.post is a asynchronous request , the functions after an asynchronous request not waiting for the asynchronous function to complete . that ' s why your alert prints with nothing , because it executes before the $.post complete . so you need to make the request synchronize , then after your function executes the alert will run

myerr="";

    $.ajax({
          url:  "/rpc/validate_song_entry",
          type: "POST",
          data: {'title':$('#title').val()},
          async:false,
          success: function(data){
             myerr=data.title;
          }
       }
    );

alert(myerr);


It is because the post is done asynchronously. You will have to use $.ajax for your issue and set it to to asynchronous.

//edit: Also have a look at that: Using $.post within a javascript function, cannot assign value to a variable?


function inside $.post(...) executes AFTER as it's done asynchronously. Your alert(myerr) executes right away before myerr was set.

0

精彩评论

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