如何将“响应”发送回提交的Ajax表单?

时间:2014-05-13 14:58:20

标签: php ajax forms response

我正在使用ajax提交表单。然后它在PHP中处理,在response我得到整个PHP / HTML代码。从PHP发回“响应”作为变量的正确方法是什么?

我的JS

$.ajax({
    url: 'index.php',
    type: 'post',
    data: {
        "myInput" : $('#myInput').val(), 
    },
    success: function(response) { 
        if(!alert(response)) {
        // do something
        }
    }
});

我的PHP只接受发布的输入值并对其进行操作:

if (isset($_POST["myInput"])) {
    // doing something - and I want to send something back
}

2 个答案:

答案 0 :(得分:2)

只需回声并退出:

if (isset($_POST["myInput"]))
{
    // doing something - and I want to send something back
    exit('Success');
}

然后在你的JS中:

success: function(response) { 
    if (response == 'Success') {
       // do something?
    }
}

例如:

test.php 单页html + php帖子处理程序

<?php

// Post Handler
if (count($_POST))
{
    // do something with posted data
    echo "You Posted: \r\n";
    print_r($_POST);
    exit();
}

// dummy data outside of the post handler, which will never be sent in response
echo "Test Page";

?>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">

$(document).ready(function()
{
    $.post('test.php', { "hello": "world" }, function(result) {
        alert(result);
    });
});

</script>

输出:

enter image description here

答案 1 :(得分:0)

$.ajax({
    url: 'index.php', // change your url or give conditional statement to print needed code
    type: 'post',
    data: {
        "myInput" : $('#myInput').val(), 
    },
    success: function(response) {
        if(!alert(response)) {
        // do something
        }
    }
});