是否可以获取并打印我在AJAx函数中传递的id。如下例所示,我在getOrder函数中传递id。我必须在OnSuccess中获取id,请指导。
由于
<script type = "text/javascript">
function getOrder(id) {
$.ajax({
type: "POST",
url: "page2.aspx/getOrderID",
data: '{ id:"' + id + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
document.getElementById('span1').innerHTML = response.d;
}
</script>
答案 0 :(得分:1)
调用外部函数时,id
参数自然不可用,因为OnSuccess
函数的范围不同。但是,如果您愿意,可以将该值传递给OnSuccess:
<script type = "text/javascript">
function getOrder(id) {
$.ajax({
type: "POST",
url: "page2.aspx/getOrderID",
data: '{ id:"' + id + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
OnSuccess(response, id);
},
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response, id) {
document.getElementById(id).innerHTML = response.d;
}
或者,您可以使用内联函数,因为它在同一范围内定义,可以直接访问id
参数:
<script type = "text/javascript">
function getOrder(id) {
$.ajax({
type: "POST",
url: "page2.aspx/getOrderID",
data: '{ id:"' + id + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
document.getElementById(id).innerHTML = response.d;
},
failure: function(response) {
alert(response.d);
}
});
}