getJson problem, it returns undefined

前端 未结 2 681
走了就别回头了
走了就别回头了 2021-01-27 06:24

hello all i have this code

var temp;
if(method==1)
  temp = $(\"#Words\").val();             //get the words from textbox
else{
  $.getJSON(\"http://localhost/mi         


        
相关标签:
2条回答
  • 2021-01-27 06:40

    you are providing the $.getJSON() function with a callback function. That doesn't get executed until the request is complete.

    0 讨论(0)
  • 2021-01-27 06:55

    it's because getJSON is ajax request, not synchronous. Try this

    var temp;
    if(method==1) {
      temp = $("#Words").val();             //get the words from textbox
      proc(temp);
    } else {
      $.getJSON("http://localhost/mine/test.js", function(data) {
          temp=data.Words;
          proc(temp);
      });
    }
    
    function proc(data){
        //do something with temp...but temp is undefined after the execution of else
    }
    
    0 讨论(0)
提交回复
热议问题