简体   繁体   English

发送json作为ajax中的数据并获得响应

[英]send json as data in ajax and get response

i want to request as json to API and get response and i tried it with postman and i got response: 我想以json的形式请求API并获得响应,并尝试用邮递员进行响应,得到响应:

json request to API: 对API的json请求:

{
"apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp"
}

response that i got in postman and it is ok 我在邮递员那里得到的回应,还可以

{
"status": 200,
"result": {
    "winner": "s",
    "options": {
        "1": "mar",
        "2": "feb",
        "3": "jan",
        "4": "aug"
    },
    "question": "how old are u?",
    "answer": 3
}

} }

my problem is i want to send ajax request and get response.i try this code but it doesnt get any response? 我的问题是我想发送ajax请求并获得response.i尝试此代码,但没有得到任何响应?

var data = {"apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp"};
$.ajax({
type:'post',
dataType:'json',
url:'http://207.154.251.233:8039/app_dev.php/question/get',
data:JSON.stringify(data),
success:(function (response) {
alert(response);
})
})

Use this modified code: 使用以下修改的代码:

var data = {"apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp"};
$.ajax({
    type:'post',
    dataType:'json',
    url:'http://207.154.251.233:8039/app_dev.php/question/get',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    crossDomain: true,
    data:JSON.stringify(data),
    success:(function (response) {
        alert(response);
    })
});

Further if your script runs from different host you must use cross origin access permission. 此外,如果您的脚本从其他主机运行,则必须使用跨源访问权限。 For this, use 为此,使用

Access-Control-Allow-Origin: http://foo.example 

If your application built in php then use: 如果您的应用程序内置于php,请使用:

header("Access-Control-Allow-Origin: *"); 
// or your script's host, e.g http://foo.example instead of "*"

The response you are getting is of type object, and will show up as [object] [object]. 您得到的响应是object类型的,将显示为[object] [object]。 You will need to JSON.stringify if you want to do an alert on it. 如果要对其发出alert ,则需要JSON.stringify I suggest using console.log instead, it's better for debugging. 我建议改用console.log ,它最好用于调试。

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

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