[英]How to post json object to web api and then receive response?
我有php代码,它工作正常,但是客户希望将其转换为javascript。 我有一个Web API服务URL,我需要通过username:password进行授权,然后将一个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: ")
});
我总是收到“发生错误:”。
希望能对您有所帮助。 谢谢。
将错误函数定义为
error: function(jqXHR, textStatus, errorThrown) {
alert('An error', jqXHR, textStatus, errorThrown );
}
了解为什么您的请求无法通过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.