2 XMLHttpRequests в одном Javascript (Dynamics CRM)

#javascript #xmlhttprequest #dynamics-crm #dynamics-crm-online

#javascript #xmlhttprequest #dynamics-crm #dynamics-crm-online

Вопрос:

В настоящее время я пытаюсь запустить 2 отдельных XMLHttpRequests в dynamics CRM Javascript для извлечения данных из 2 разных объектов и запуска кода в зависимости от того, что извлекается..

Я сделал все возможное, чтобы попытаться отредактировать некоторые имена по соображениям безопасности, но предпосылка та же. Моя основная проблема заключается в том, что первый запуск XMLHttpRequest (баннер RA) работает нормально, но затем при втором запуске (баннер состояния) возвращаемое состояние готовности равно 2 и останавливается.

 function FormBanners(formContext) {
    //Clear the existing banners
    formContext.ui.clearFormNotification("Notif1");
    formContext.ui.clearFormNotification("Notif2");

    //Get the customer/rep
    var customer = formContext.getAttribute("customerid").getValue();
    var rep = formContext.getAttribute("representative").getValue();
    var contact;

    //use the rep if there is one else use the customer
    if (rep != null) {
        contact = rep;
    }
    else if (customer!= null) {
        contact = customer;
    }

    //Get the account
    var account = formContext.getAttribute("accountfield").getValue();

    //As there is a requirement for 2 XMLHTTPRequests we have to queue them
    var requestURLs = new Array();

    //There will always be a customers or rep on the form
    requestURLs.push(Xrm.Page.context.getClientUrl()   "/api/data/v9.1/contacts?$select=new_RA,new_SC,new_VC,new_PRamp;$filter=contactid eq "   contact[0].id   "", true);

    //there may not be an account
    if (account) {
        requestURLs.push(Xrm.Page.context.getClientUrl()   "/api/data/v9.1/accounts?$select=_new_statusLookup_valueamp;$filter=accountid eq "   account[0].id   "", true);
    }

    var current = 0;

    function getURL(url) {
        var req = new XMLHttpRequest();
        req.open("GET", requestURLs[current]);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations="*"");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var result = JSON.parse(req.response);
                    // Creation of the RA Banner
                    if (current == 0) {
                        var RA = result.value[0]["new_RA@OData.Community.Display.V1.FormattedValue"];
                        var SC = result.value[0]["new_SC@OData.Community.Display.V1.FormattedValue"];
                        var VC = result.value[0]["new_VC@OData.Community.Display.V1.FormattedValue"];
                        var PR = result.value[0]["new_PR@OData.Community.Display.V1.FormattedValue"];
                        var Notif = "";

                        //Only create a notification if any of the above contain "Yes"
                        if (RA == "Yes" || SC == "Yes" || VC == "Yes" || PR == "Yes") { Notif = "The Customer/Rep has:" }
                        if (RA == "Yes") { Notif = Notif   " RA,"; }
                        if (SC == "Yes") { Notif = Notif   " SC,"}
                        if (VC == "Yes") { Notif = Notif   " VC,"}
                        if (PR == "Yes") { Notif = Notif   " PR."}

                        if (Notif != "") {
                            formContext.ui.setFormNotification(Notif, "INFO", "Notif1");
                        }
                    }
                    //Creation of the Status Banner
                    else if (current == 1) {
                        status = results.value[i]["_new_statusLookup_value"];
                        if (status) {
                            if (status[0].name != "Open")
                                var Notif = "The status for the organisation on this case is "   status[0].name   ".";
                            formContext.ui.setFormNotification(Notif, "INFO", "Notif2");
                        }
                    }

                      current;
                    if (current < requestURLs.length) {
                        getURL(requestURLs[current]);
                    }

                } else {
                    Xrm.Utility.alertDialog(req.statusText);
                }
            }
        }; req.send();
    }

    getURL(requestURLs[current]);
}
 

Кто-нибудь может мне помочь?

Комментарии:

1. Можете ли вы удалить функцию getURL и сохранить ее вне функции FormBanners?

Ответ №1:

Итак, в моем примере я допустил много ошибок. Следуя совету Аруна, я разделил функцию, что значительно упростило отладку.. вместо этого он не выполнял запрос XMLHTTP, потому что это работало нормально, но firefox зависал при отладке.

Итак, мои проблемы заключались в том, что я был во второй части:

  • Для результатов использовалось значение i (i больше не был определен)
  • Получение «_new_statusLookup_value» будет предоставлять только идентификатор guid для поиска, который я бы вместо этого хотел «_new_statusLookup_value@OData.Сообщество.Display.V1.FormattedValue»
  • Давайте не будем игнорировать тот факт, что, поскольку я скопировал и вставил много итераций этого кода, я также использовал «результаты» вместо «результата».

Много маленьких ошибок.. но это происходит! Спасибо за помощь, просто показывает .. опечатки — наше падение!