2012-04-23 149 views
3

我需要爲我的成功回調使用外部函數,我不知道如何將json對象傳遞給我的函數。Jquery ajax外部回調函數

$.ajax({ 
url:"get_box.php", 
type:"POST", 
data:data, 
dataType:"json", 
success: myFunction(data); 
    }); 

而我的函數看起來是這樣的:

function myFunction(result2){ 
... 
} 

的錯誤是:不確定RESULT2 ...

回答

11

嘗試這種方式,

success: function(data){ 
     myFunction(data); 
    }); 

或...

success: myFunction 
    }); 
1

您如何實施成功和失敗回調方法(jquery documentation)。你也可以連接這些,而不是在最初的AJAX設置對象爲他們提供像這樣:

Here is a fiddle

jQuery.ajax({ 
    // basic settings 
}).done(function(response) { 
    // do something when the request is resolved 
    myFunction(response); 
}).fail(function(jqXHR, textStatus) { 
    // when it fails you might want to set a default value or whatever? 
}).always(function() { 
    // maybe there is something you always want to do? 
});​ 
0
<script> 
function fun(){ 
    $.ajax({ 
     url : "http://cdacmumbai.in/Server.jsp?out=json&callback=?", 
     dataType: "json", 
     contentType: "application/json;charset=utf-8", 
     type: "GET", 
     success: function (output) { 
      var data = eval(output); 
      document.getElementById("datetime").innerHTML = "Server Date&Time: "+data.servertime; 
      document.getElementById("hostname").innerHTML = "Server Hostname: "+data.hostname; 
      document.getElementById("serverip").innerHTML = "Server IP Address: "+data.serverip; 
      } 
     }); 
     } 
</script>