为Ajax调用返回的数据

时间:2016-06-28 12:49:01

标签: php jquery ajax return

我正在尝试返回Ajax的数据,但我仍然不清楚某些事情:
我的表格:

<form id="checkitem" class="form-horizontal">
 <input type="text" name="item1"><br><br>
 <input type="submit" value="Submit">
</form>

Ajax电话:

<script>
$(document).ready(function(){
    $('#checkitem').submit(function(){
        $.ajax({
            type: 'POST',
            url: 'operations.php?r=checkitem', 
            data: $(this).serialize()
        });    
     });
}); 
</script>

我的PHP代码(对于operations.php?r = checkitem):

$item1 = mysql_real_escape_string($_POST['item1']);
include ("data.php"); 
$query = mysql_query("INSERT INTO Itemlist (item1, ins_date) VALUES ('$item1',now()");
if (!$query)
{
    die('Invalid query: ' . mysql_error());
}
echo "Item1 has been added";

如何从页面operations.php

返回echo值或任何其他php变量

编辑:
根据你的建议,我应该使用成功函数:

 success : function(response){
             alert(response); //Do whatever you want to do with this

我的问题是,什么是回应?这是从其他页面回应的所有内容吗?或其他页面的HTML代码?

日Thnx

3 个答案:

答案 0 :(得分:2)

jquery的ajax函数有一个成功的回调函数,你可以从你调用的ajax页面中检索数据:

$.ajax({
    type: 'POST',
    url: 'operations.php?r=checkitem', 
    data: $(this).serialize(),
    success: function(result) {
        console.log(result);
        // do what you want with the result here
        // if it's html you could do $('.elem').html(result);
    }
})

更好的是使用类型键指定您期望的数据类型:(类型:'json')或(类型:'text / html)。 并在您的PHP脚本中,发送标题!

答案 1 :(得分:2)

你可以这样做。

AJAX有各种callback functions,成功就是其中之一。您可以使用其他人,例如error, complete

当AJAX请求成功执行时,将调用

success。这将在我们的PHP页面中提供response textecho的使用print

<script>
$(document).ready(function(){
   $('#checkitem').submit(function(){
     $.ajax({
         type: 'POST',
         url: 'operations.php?r=checkitem', 
         data: $(this).serialize(),
         success : function(response){
             alert(response); //Do whatever you want to do with this
         }
    })    
   });
 }); 
</script>

答案 2 :(得分:2)

或使用延迟方式

$.ajax({
    type: 'POST',
    url: 'operations.php?r=checkitem', 
    data: $(this).serialize()})
.done(function(result){
    console.log(result);
})
.fail(function(error){
   console.log(error);
});
相关问题