【问题标题】:Data returned for Ajax call为 Ajax 调用返回的数据
【发布时间】:2016-10-30 19:28:41
【问题描述】:

我正在尝试为 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";

如何从页面操作返回 echo 值或任何其他 php 变量

编辑:
根据您的建议,我应该使用成功功能:

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

我的问题是,什么是响应?这一切都是从其他页面得到回应的吗?还是其他页面的 HTML 代码?

谢谢

【问题讨论】:

  • 使用 AJAX 的成功部分。阅读它
  • 首先,检查您的 PHP 代码,因为您的 ' 不匹配。其次,这可能会有所帮助:stackoverflow.com/questions/7064391/…
  • response 是一个参数。在这种情况下,它会从请求的页面获取文本/输出。

标签: php jquery ajax return


【解决方案1】:

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);
    }
})

最好使用 type 键指定您期望的数据类型:例如 (type: 'json') 或 (type: 'text/html)。 并在您的 php 脚本中发送标头!

【讨论】:

    【解决方案2】:

    你可以这样做。

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

    success 会在 AJAX 请求成功执行时被调用。这将提供使用 response text,我们在 PHP 页面中使用 echoprint

    <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>
    

    【讨论】:

    • 如果我想从php页面返回一个PHP数组怎么办?
    • 回显 json_encode($arr);在 PHP 页面上,然后在 JS 端使用 JSON.parse。
    • @Dxtr 不用谢我们是来互相帮助的
    【解决方案3】:

    或使用延迟方式

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多