ajax函数参数成功

时间:2015-06-17 23:29:25

标签: javascript jquery json

是否可以获取并打印我在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>

1 个答案:

答案 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);
            }
        });
    }