简体   繁体   English

如何通过jquery ajax检查和接收api调用的结果

[英]how to check and receive result for the api call over jquery ajax

I'm trying hit the API over jquery ajax with the URL and parameter with post method.我正在尝试使用带有 post 方法的 URL 和参数通过 jquery ajax 命中 API。 here I'm checking delivery is available or not for the given Pincode for one of e-com website,please help me out on how to check or receive data from the API response.在这里,我正在检查某个 e-com 网站的给定 Pincode 是否可以交付,请帮助我了解如何从 API 响应中检查或接收数据。

My Script :我的脚本:

<script type="text/javascript"> 
$(document).ready(function () {
    $('#check').click(function(){
        var api_url = 'http://example.com/webservices/b2cpincodecheck.jsp';
        var key = '4A8DA5E635656'; 
        var pincode = 604408 ;

        if(pincode=="") {
            alert("please enter the pincode");
        } else {
            $.ajax({
                url:api_url+"?reqid="+key+"&pincode="+pincode,
                dataType: "text/json",
                type: "POST",
                success: function(result){
                    //console.log(result);
                    if(result) {
                        alert("Delivery is available!");
                    } else {
                        alert("Delivery is not available!");
                    }
                }
            })
        }  
    });
});
</script> 

As per the API response in the given document, I would get data in XML format根据给定文档中的 API 响应,我将获得 XML 格式的数据

Their response :他们的回应:

<response>
<result>successful</result>
<pinCode>604408</pinCode>
<ouCode>abc</ouCode>
</response>

Please help me out on how to check or receive data from the API response.请帮助我了解如何从 API 响应中检查或接收数据。 Thanks in advance.提前致谢。

jQuery AJAX Method is to load data from external website by calling APIs, and get the response in JSON or XML formats. jQuery AJAX方法是通过调用 API 从外部网站加载数据,并获得JSONXML格式的响应。 this example shows you how easy it is to make such API calls in jQuery AJAX .something like this这个例子向你展示了在jQuery AJAX进行这样的 API 调用是多么容易。像这样

$(document).ready(function () {
    $("#submit").click(function (e) {
        var validate = Validate();
        $("#message").html(validate);
        if (validate.length == 0) {
            $.ajax({
                type: "POST",
                url: "http://api.openweathermap.org/data/2.5/weather?id=" + $("#citySelect").val() + "&appid=API-KEY&units=metric",
                dataType: "json",
                success: function (result, status, xhr) {
                    var table = $("<p>Weather Description</p>");

                    table.append("<p>City:</p>" + result["name"] + "</p>");
                    table.append("<p>Country:</p>" + result["sys"]["country"] + "</p>");
                    table.append("<p>Current Temperature:</p>" + result["main"]["temp"] + "°C</p>");
                    table.append("<p>Humidity:</p>" + result["main"]["humidity"] + "</p>");
                    table.append("<tr><td>Weather:</p>" + result["weather"][0]["description"] + "</p>");

                    $("#message").html(p);
                },
                error: function (xhr, status, error) {
                    alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                }
            });
        }
    });

To get result <div id="message"></div>获取结果<div id="message"></div>

 $(document).ready(function () { $('#check').click(function(){ var api_url = 'http://example.com/webservices/b2cpincodecheck.jsp'; var key = '4A8DA5E635656'; var pincode = 604408 ; if(pincode=="") { alert("please enter the pincode"); } else { $.ajax({ url:api_url+"?reqid="+key+"&pincode="+pincode, dataType: "xml", type: "POST", success: function(result, status, jqXHR){ console.log(loadData(result || jqXHR.responseText)) } }) } }); }); function loadData(xml) { var incubator; if (typeof xml === "string") { incubator = document.createElement("div"); incubator.innerHTML = xml; } else { incubator = xml; } return { "response": { "result": incubator.querySelector("result").textContent, "pinCode": incubator.querySelector("pinCode").textContent, "ouCode": incubator.querySelector("ouCode").textContent, } } } function xmlToObject(xml) { var incubator = document.createElement("div"); incubator.innerHTML = xml; return Array.prototype.map.call(incubator.childNodes, nodeToObject) } function nodeToObject(node) { if (node.nodeType === Node.ELEMENT_NODE) { return { nodeName: node.nodeName.toLowerCase(), attributes: nodeAttributesToObject(node), childNodes: Array.prototype.map.call(node.childNodes, nodeToObject) }; } if (node.nodeType === Node.TEXT_NODE) { return node.textContent; } } function nodeAttributesToObject(node) { var result = {}; Array.prototype.forEach.call(node.attributes, function (attr) { result[attr.name] = attr.value; }); return result; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Here is two example of data extraction from xml :这是从 xml 中提取数据的两个示例:

  1. the function loadData get exaclty the field you expect函数loadData得到你期望的字段
  2. the function xmlToObject can help you to walk an XML as if it was a simple JavaScript object.函数xmlToObject可以帮助您将 XML 视为一个简单的 JavaScript 对象。

Please be careful: jQuery ajax setting dataType should be empty or the direct format (ie: "json" , not "text/json" ), here you should set it to "xml" .请注意: jQuery ajax 设置dataType应为空或直接格式(即: "json" ,而不是"text/json" ),此处应将其设置为"xml"

Hope it will help you!希望它会帮助你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM