javascript嵌入式函数和嵌入式变量范围

时间:2014-05-08 22:15:51

标签: javascript jquery scope

我正在编写一个小应用程序,它将使用jQuery ajax调用来调用第三方API。我想使以下函数“通用”,但在“done()”ajax方法的最内层函数中遇到变量范围问题。该功能是返回好东西的地方。我希望将键值对放在传递到APICall函数的“result”对象中,但我不知道如何在那里引用它。

我不认为我可以在“完成”部分修改功能参数列表吗?我只是尝试将传入的“结果”添加到“完成”函数中,并且没有语法问题,但它无法正常工作。

想法?

function APICall(method, username, password, payload, result) {
    var wsUrl = "https://localhost.my.company.org/API/Service.asmx";

    var soapRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<soap:Envelope \n"
            + "    soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"
            + "    xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" \n"
            + "    xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"
            + "    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n"
            + "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> \n"
            + "  <soap:Body> \n"
            + "    <__METHOD__ xmlns=\"http://THIRD-PARTY.API.Web.Service/\"> \n"
            + "      <UserName>__USERNAME__</UserName> \n"
            + "      <Password>__PASSWORD__</Password> \n"
            + "      __PAYLOAD__ \n" + "    </__METHOD__> \n"
            + "  </soap:Body> \n" + "</soap:Envelope>\n";

    soapRequest = soapRequest.replace(/__METHOD__/g, method);
    soapRequest = soapRequest.replace(/__USERNAME__/g, username);
    soapRequest = soapRequest.replace(/__PASSWORD__/g, password);
    soapRequest = soapRequest.replace(/__PAYLOAD__/g, payload);

    $.ajax({
            type : "POST",
            headers : {
                    SOAPAction : '"http://THIRD-PARTY.API.Web.Service/' + method + '"'
            },
            url : wsUrl,
            contentType : "text/xml",
            dataType : "xml",
            data : soapRequest,
            error : processAJAXError
     }).done(
            function(data, textStatus, jqXHR) {
                    $($.parseXML($(data).find(method + 'Result').text())).find(
                            'Data').each(
                            function(key, val) {
                                result[$(val).find('Room').text()] = $(val).find(
                                        'ID').text();
                                    console.log($(val).find('Room').text() + ' => '
                                            + $(val).find('ID').text());
                            });
             });
}

1 个答案:

答案 0 :(得分:0)

尝试bind();

.done(
    function(data, textStatus, jqXHR) {                  
        .
        .
        .

    }.bind(result));