如何POST ajax并获得响应

How to POST ajax and get response?

本文关键字:响应 POST ajax 如何      更新时间:2023-09-26

我的表单、帖子和响应有问题。在我的表单中,我用ajax post:调用一个函数(javascript)

var vars = "test="+test;
$.ajax({
    type: "POST",
    url: "index.php",
    data: vars
}).done(function(data) {
    alert(data);
}).fail(function(data) {
    alert(data);
});

在index.php中,我收到所有数据:

<?php
    $test = $_POST['test'];
    //do something
?>

之后我必须将一个值返回给以前的php。我该怎么办??感谢

与为任何其他HTTP请求发回数据的方式相同。

header("Content-Type: text/plain");  # Avoid introducing XSS vulnerabilities
echo $test;

如果它是一个需要返回的简单值,您只需echo它,它就会作为响应返回。

如果需要返回更复杂的结构,可以将其存储在PHP数组中,比如$response,然后使用echo json_encode($response);将其输出回javascript。

这可能有助于

Javascript

var vars = { test : "test" };
$.ajax({
    type: "POST",
    url: "index.php",
    dataType : 'json',
    data: vars,
    success : function(data) {
        console.log(data);
    },
    error : function(resp) {
        console.log(resp.responseText);
    }
});

PHP

<?php
    $test = $_POST['test'];
    echo json_encode($test);
?>

尝试并检查控制台日志

var vars = "test="+test;
$.ajax({
    type: "POST",
    url: "index.php",
    data: vars
    success: function(html){
         alert(html)
    }
});

在index.php中,输入以下代码并检查

<?php
    $test = $_POST['test'];
    //do something
    echo $test
?>

如果必须以JSON格式返回数据,则使用

echo json_encode($test);

否则,您可以简单地在ajax响应中回显所需的变量。即

echo $test;