我有一个返回所有claim_id
的ajax。从claim_id
开始,我调用另一个ajax来获取此claim_id
的所有字段。但我无法将第一个ajax中claim_id
的值传递给内部ajax中的success函数。它将始终返回claim_id
的最后一个值。我怎样才能分别得到claim_id
?
$(document).ready( function () {
var c_id = document.getElementById("c_id").value;
$.ajax({
url: '../rest/CategoryService/compcategory/'+c_id,
type: 'POST',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(data) {
//get the claim id
for (i in data){
var claim_id = data[i].iD;
// alert(claim_id);
//get all the fields for the claim id
$.ajax({
url: '../rest/CategoryService/fieldcategory/'+claim_id,
type: 'POST',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(data2) {
var textfield = "";
//construct the header fields
textfield += "<th>Sub Category</th>";
for (z in data2){
var field = data2[z].field;
textfield += "<th>"+field+"</th>";
}
textfield += "<th>Action</th>";
alert(claim_id);
alert(textfield);
$("#tabledata"+claim_id+" thead").append(
"<tr>"+textfield+"</tr>");
},
});
}
},
});
} );
答案 0 :(得分:0)
您可以在第二个ajax
params
中定义它,然后在成功函数中使用this.param_name
var claim_id = data[i].iD;
$.ajax({
url: '../rest/CategoryService/fieldcategory/'+claim_id,
claim_id: claim_id, // defining your custome params here
/*your other params*/
success: function(data2) {
alert(this.claim_id); // will alert your var claim_id variable
}
});
或第二个选项选项是在js中定义全局变量并成功使用
答案 1 :(得分:0)
基本上你的代码中的问题是for循环不会等待ajax调用完成。这就是你永远获得最后claim_id
的原因。请尝试以下代码:
$(document).ready( function () {
var c_id = document.getElementById("c_id").value;
$.ajax({
url: '../rest/CategoryService/compcategory/'+c_id,
type: 'POST',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(data) {
var getClaimData = function(pointer, dataLength) {
var claim_id = data[pointer].iD;
$.ajax({
url: '../rest/CategoryService/fieldcategory/'+claim_id,
type: 'POST',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(data2) {
var textfield = "";
//construct the header fields
textfield += "<th>Sub Category</th>";
for (z in data2){
var field = data2[z].field;
textfield += "<th>"+field+"</th>";
}
textfield += "<th>Action</th>";
alert(claim_id);
alert(textfield);
$("#tabledata"+claim_id+" thead").append(
"<tr>"+textfield+"</tr>");
pointer++;
if(pointer < dataLength) {
getClaimData(pointer, dataLength);
}
},
});
};
getClaimData(0, data.length);
},
});
});