简体   繁体   English

如何使用 ajax javascript 调用服务?

[英]how to call a service using ajax javascript?

I'm learning programing, could you explain me how to call a service using ajax javascript?我正在学习编程,你能解释一下如何使用 ajax javascript 调用服务吗?

Service information:服务信息:

I've tested this service in postman我已经在 postman 中测试了这项服务在此处输入图像描述

Service answer:服务解答:

{
    "respuesta": [
        {
            "estado": "Correcto.",
            "identificacion": "98122811999",
            "imagen": "return string Base 64 format"
        }
    ]
}

Using JQuery:使用 JQuery:

 $.ajax({ type: 'POST', url: 'https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar', dataType: 'json', data:{"identificacion":["98122811999"]} contentType: "application/json" beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', make_base_auth("admi", "admi")); }, success: function (data,status) { //do what you want with the data after success //in this example the response will be promoted in the browser console console.log(data); }); }); function make_base_auth(user, password) { var tok = user + ':' + password; var hash = btoa(tok); return 'Basic ' + hash; }

You can call your above RestEndpoint using below:您可以使用以下方法调用上面的 RestEndpoint:

xmlhttp.open("POST", "/EndpointURI", true);
 
xmlhttp.onreadystatechange = function() 
{
    if (this.readyState == 4 && this.status == 200) 
    {
        //Use parse() method to convert JSON string to JSON object
        var responseJsonObj = JSON.parse(this.responseText);
 
        //use response
    }
};
 
var jsonData = {"name" : "yourData"};
xmlhttp.send( JSON.stringify( jsonData ) ); 

For Authentication use this:对于身份验证,请使用:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://EndPointURI", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('userName:password'));
xhr.onload = function () {
    console.log(xhr.responseText);
};
xhr.send();

For authentication part, use JQuery then it will easy for the implementation and as well for understanding.对于身份验证部分,使用 JQuery 这样将易于实现和理解。 as now aday no body use basic xmlhttp for calling api in javascript, last time i used was a 2003 developed application.现在没有人使用基本的 xmlhttp 在 javascript 中调用 api,我上次使用的是 2003 开发的应用程序。

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

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