简体   繁体   English

如何将json对象发布到Web API,然后接收响应?

[英]How to post json object to web api and then receive response?

I have php code, it works fine, but the customer want to convert it into javascript. 我有php代码,它工作正常,但是客户希望将其转换为javascript。 I have a web api service url, i need to authorize by username:password then post a json object to the web api url to receive data(also in json type). 我有一个Web API服务URL,我需要通过username:password进行授权,然后将一个json对象发布到该Web API URL中以接收数据(也是json类型)。

Here is my php code: 这是我的PHP代码:

curl_setopt($ch, CURLOPT_URL, $MyWebApiUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json' )
);

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);           //  curl authentication

curl_setopt($ch, CURLOPT_USERPWD, "$Username:$Password");       //  curl authentication

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS,$MyPostJsonObject);

$str=  curl_exec($ch);

curl_close($ch);

$data = json_decode($str)

This is my javascript code so far 到目前为止,这是我的JavaScript代码

$.ajax({
            type: 'POST',
            url: MyWebApiUrl,            
            beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic  XXXXXXXXXX");},
            data: JSON.stringify(MyPostJsonObject),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                alert(data.d);
            },
            error: alert("An error occurred: ")
        });

I always receive "An error occurred: ". 我总是收到“发生错误:”。

Hope you can help. 希望能对您有所帮助。 Thank you. 谢谢。

Define error function as 将错误函数定义为

error: function(jqXHR, textStatus, errorThrown) {
    alert('An error', jqXHR, textStatus, errorThrown );
}

to understand why your request can't pass. 了解为什么您的请求无法通过。

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

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