Calling External API with Javascript

前端 未结 5 1811
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 03:33

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can\'t figure out how to make this call or what tool

5条回答
  •  臣服心动
    2021-02-14 04:20

    When you want to use different domain ajax call then you need to use the JSONP datatype which will allow browser to do cross domain request.

    Here is more document for the JSONP : https://learn.jquery.com/ajax/working-with-jsonp/

    var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
    var response = $.ajax({
               url: "http://" + environment + "/vizportal/api/web/v1/getViews",
               method: "post",
               dataType:'jsonp',
               data: JSON.stringify(body),
               headers: {
                'Content-Type': 'text/plain',
                'X-XSRF-TOKEN' : XSRFToken,
                'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
               },
               success:function(response){
                    alert("success");
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) { 
                    alert("Status: " + textStatus); alert("Error: " + errorThrown); 
                } 
            });
    

提交回复
热议问题