我有一個JsTree,它基於從AJAX調用中接收到的JSON數據獲取。這是AJAX調用。我需要從jQuery中的.ajax函數「success」中返回
function sendQuery(){
$.ajax({
context: this,
url: 'http://localhost:8080/testMain',
type: 'GET',
dataType: 'text',
success: function(data) {
// ^^^^ Need for sendQuery() to return DATA
},
error: function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
});
}
我知道這裏有一個範圍問題。在JavaScript中,變量是根據聲明函數定義的。我只是不知道如何從sendQuery()中返回,然後將其作爲參數傳遞給另一個將解析JSON的函數,該JSON是另一個樹的舞臺參數。有點令人沮喪的是,這件作品在發條上並沒有像我在Java中習慣的那樣簡單。非常感謝幫助,如果有效,那麼肯定會接受。乾杯
編輯#1:好的基於這些答案,我相信如果我以這種方式更改我的代碼,它將允許數據退出.ajax函數。還有一個問題是如何讓它重新回到程序的流程中。
function sendQuery(){
$.ajax({
context: this,
url: 'http://localhost:8080/testMain',
type: 'GET',
dataType: 'text',
success: getJson,
error: function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
});
}
function getJson(data){
alert("Transmission Success.");
alert(data);
var obj = $.parseJSON(data);
alert("Parsing JSON Success.");
var apples = obj.apples;
alert(apples);
return apples;
}
好吧,那麼現在我怎樣才能將APPLES變量放到調用鏈中來調用樹的數據呢?
我需要將APPLES變量提供給將處理數據的函數。
編輯#2使用回調:
我花了第二環繞回調的想法我的頭。這是我能夠做到的。
這是我的原始樹代碼,它調用一系列函數來完成不同的事情,但最終以樹的形式接收數據。
$(function() {
$("#client_tree").jstree({
"json_data": {"data": attachTree(stageTreeData(getJson(sendQuery())))},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) {
var msg = data.rslt.obj.attr("id");
alert(msg);
});
});
我此刻想獲得通過Ajax的數據,在sendQuery()方法,然後將其與數據等返回...]
我改變了它咯,現在我不來電sendQuery(),jQuery調用它。
$(function(){
$.ajax({
context: this,
url: 'http://localhost:8080/testMain',
type: 'GET',
dataType: 'text',
success: loadTree,
error: function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
});
});
也改變了我的樹加載代碼有點...
function loadTree(data){
$("#client_tree").jstree({
"json_data": {"data": attachTree(stageTreeData(getJson(data)))},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) {
var msg = data.rslt.obj.attr("id");
alert(msg);
});
}
我沒有錯誤,沒有例外並填充樹。
謝謝大家的幫忙!
編輯#3修復了一些小東西:
移到Alert() call in jQuery not displaying, called from within a JsTree
哦,所以如果我傳遞一個像success這樣的函數:functionName它會將數據傳回給函數。太棒了。非常感謝。我會盡力。 –
yes ..'success:functionName'將與'success:function(data){functionName(data)}相同' – charlietfl
OK剛剛對問題進行了編輯,我需要將此數據發送給函數調用。有空的時候請檢查一下。謝謝 –