0

可能重复:
jQuery:ajax调用成功后返回数据

因此,我正在调用 Sharepoint 服务并尝试返回一些值以供其他地方使用,并且我正在尝试声明一个窗口变量来执行此操作。看起来很简单,但是在 responseXML 函数之外未定义窗口变量。

userName = "";

var soapEnv =
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:tns='http://schemas.microsoft.com/sharepoint/soap/'> \
    <soap:Body> \
        <GetUserProfileByName xmlns='http://microsoft.com/webservices/SharePointPortalServer/UserProfileService'> \
            <AccountName></AccountName> \
        </GetUserProfileByName> \
    </soap:Body> \
</soap:Envelope>";

$.ajax({
    url: "/_vti_bin/userprofileservice.asmx",
    type: "POST",
    dataType: "xml",
    data: soapEnv,
    complete: processResult,
    contentType: "text/xml; charset='utf-8'"    
});

function processResult(xData, status) {
    $(xData.responseXML).find("PropertyData > Name:contains('FirstName')").each(function() {
        window.FirstName = $(this).parent().find("Values").text();
    });

    $(xData.responseXML).find("PropertyData > Name:contains('LastName')").each(function() {
        window.LastName = $(this).parent().find("Values").text();
    });

}

    userName += window.FirstName;
    userName += " " + window.LastName;
    console.log(userName);
4

2 回答 2

0

异步调用改变了执行的顺序。processResult will be called after window.FirstName; and window.LastName; is assigned to userName,我试图通过调用将显示窗口的警报来描述序列。如果在 processResult 正文执行之前定义,FirstName 可用。

window.FirstName = "First Name: Assigned before ajax call";
window.LastName = "Last Name: Assigned before ajax call";

function processResult(xData, status) {
    $(xData.responseXML).find("PropertyData > Name:contains('FirstName')").each(function() {
        window.FirstName = $(this).parent().find("Values").text();
    });

    $(xData.responseXML).find("PropertyData > Name:contains('LastName')").each(function() {
        window.LastName = $(this).parent().find("Values").text();
    });

   userName += window.FirstName;
   userName += " " + window.LastName;
   alert("After ajax response UserName: " + userName);    
}

userName += window.FirstName;
userName += " " + window.LastName;
alert("Before ajax response UserName: " + userName);
于 2012-11-09T19:09:09.170 回答
0

您正试图在 AJAX 调用完成之前window.FirstName访问。window.LastName你需要把它放在你的回调函数中:

function processResult(xData, status) {
    $(xData.responseXML).find("PropertyData > Name:contains('FirstName')").each(function() {
        window.FirstName = $(this).parent().find("Values").text();
    });

    $(xData.responseXML).find("PropertyData > Name:contains('LastName')").each(function() {
        window.LastName = $(this).parent().find("Values").text();
    });

    userName += window.FirstName;
    userName += " " + window.LastName;
    console.log(userName);

}
于 2012-11-09T19:01:42.643 回答