[英]Trouble reading ajax post response
I am working on a website and I am trying to connect JavaScript and php using ajax. 我正在一个网站上工作,并且尝试使用ajax连接JavaScript和php。 I have a problem with reading ajax response.
我在阅读ajax响应时遇到问题。
I have one php script which has the following code: 我有一个PHP脚本,其中包含以下代码:
<?php
echo "1";
And a function written in JavaScript ecma 6, which has the following code: 还有一个用JavaScript ecma 6编写的函数,它具有以下代码:
loginUser(username, password) {
return new Promise((resolve, reject) => {
var request = require('ajax-request');
request.post(
{
url: 'http://swiftservice.psoftwarestudio.com/Admin.php',
data: {
username: username,
password: password
},
headers: {}
}
, (data) => {
resolve(data);
}
);
});
}
When I debug, the data is always null. 当我调试时,数据始终为空。 I am very new at web programming especially whit ajax.
我是Web编程的新手,尤其是ajax。 I hope someone can point me to the error, thanks.
希望有人能指出我的错误,谢谢。
I looked in the documentation of the ajax-request
module and noticed that the callback takes 3 arguments: function(err, res, body) {
. 我查看了
ajax-request
模块的文档,发现回调带有3个参数: function(err, res, body) {
。
Perhaps the required data is in the third? 也许所需数据在第三位?
You need to parse the data
you get back from your AJAX call into a JSON Object, as what you get is the String representation of it: 您需要将从AJAX调用返回的
data
解析为JSON对象,因为获得的是它的String表示形式:
loginUser(username, password) {
return new Promise((resolve, reject) => {
var request = require('ajax-request');
request.post(
{
url: 'http://swiftservice.psoftwarestudio.com/Admin.php',
data: {
username: username,
password: password
},
headers: {}
}
, (data) => {
resolve(JSON.parse(data));
}
);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.