【问题标题】:How to post json object to web api and then receive response?如何将 json 对象发布到 web api 然后接收响应?
【发布时间】:2014-09-14 12:55:49
【问题描述】:

我有 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: ")
        });

我总是收到“发生错误:”。

希望您能提供帮助。谢谢。

【问题讨论】:

    标签: javascript php json post authorization


    【解决方案1】:

    定义误差函数为

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

    了解您的请求为何无法通过。

    【讨论】:

    • jqXHR 对象包含有关请求的信息。例如,status 和 responseText 属性包含主要信息。将警报消息编辑到alert('An error', jqXHR.status, jqXHR.responseText );。见w3schools.com/dom/dom_http.asp
    猜你喜欢
    • 2015-03-22
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多