如何发布json对象到web api,然后接收响应


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

我有php代码,它工作得很好,但客户想把它转换成javascript。我有一个web api服务url,我需要通过用户名:密码授权,然后发布一个json对象到web api url接收数据(也在json类型)。

下面是我的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)

这是目前为止我的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: ")
        });

我总是收到"An error occurred: ".

希望你能帮忙。谢谢你。

定义错误函数

error: function(jqXHR, textStatus, errorThrown) {
    alert('An error', jqXHR, textStatus, errorThrown );
}
相关文章: