所以这是我的问题,我使用AJAX(jQuery)将表单发布到process.php
,但该页面实际上需要回显诸如apple
或plum
之类的响应。我不确定如何从process.php
获取响应并将其存储为变量...
这是我到目前为止的代码:
<script type="text/javascript">
function returnwasset(){
alert('return sent');
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
success function(){
//echo what the server sent back...
}
});
}
</script>
我还需要在json的process.php
中回应响应吗?或者纯文本会没事?
很抱歉,如果这听起来像个愚蠢的问题,这是我第一次在Ajax中做这样的事情。
PS:如何在上面的代码中命名POST请求?
答案 0 :(得分:39)
<?php echo 'apple'; ?>
几乎就是服务器上所需的全部内容。
对于JS方面,服务器端脚本的输出作为参数传递给成功处理函数,所以你有
success: function(data) {
alert(data); // apple
}
答案 1 :(得分:24)
好的做法是这样使用:
$.ajax({
type: "POST",
url: "/ajax/request.html",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
console.log(response.blablabla);
// put on console what server sent back...
}
});
和php部分是:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo json_encode(array("blablabla"=>$variable));
}
?>
答案 2 :(得分:15)
<script type="text/javascript">
function returnwasset(){
alert('return sent');
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
dataType:'text'; //or HTML, JSON, etc.
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
</script>
答案 3 :(得分:10)
在PHP文件中,当您回显数据时使用json_encode(http://php.net/manual/en/function.json-encode.php)
e.g。
<?php
//plum or data...
$output = array("data","plum");
echo json_encode($output);
?>
在你的javascript代码中,当你的ajax完成时,json编码的响应数据可以变成这样的js数组:
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
success function(json_data){
var data_array = $.parseJSON(json_data);
//access your data like this:
var plum_or_whatever = data_array['output'];.
//continue from here...
}
});
答案 4 :(得分:0)
it("Updating User details: ", function (done) {
this.timeout(300);
server
.put(apiUrl + "/user")
.send({
"name": "Vinay Pandya",
"photo": "http://tamilcinema.com/wp-content/uploads/2015/05/madhavan.jpg",
"email": "mail@mail.com",
"gender": "M"
})
.set({"Authorization": token})
.expect(200)
.end(function (err, res) {
if (err)
throw err;
res.status.should.equal(200);
res.body.status.should.equal("success");
//console.info(JSON.stringify(res.body));
done();
});
});