将Ajax数据发送到当前页面

时间:2014-04-11 15:47:24

标签: php jquery ajax

我有一些数据将用作图片库的一部分,但我不想在加载数据之间刷新页面(我希望保持可见的界面项)。但是,当我通过ajax JS将数据提交到同一页面时,注册成功执行代码(警告框显示)但PHP无法收集数据。

我的JQuery看起来像这样

$(".gallery_thumbnail").click(function(){
  var id=$(this).attr("data-id");
  $.ajax({
    type: "GET",
    url: "test.php",
    data: {newid:id},
    dataType: 'text',
    success:function(result){
      // Test what is returned from the server
      alert(result);
    }
  });
});

我的PHP看起来像这样\

if(isset($_GET['newid'])){
  echo "success";
}
else{
  echo "fail";
}

我已经看过类似的问题,并尝试复制和粘贴答案,但我似乎无法让这个工作。我也尝试过url参数:

http://localhost/test.php and simply removing the url parameter altogther.

2 个答案:

答案 0 :(得分:1)

检查请求是否是ajax,然后执行ajax处理

// this code should go before any of the web page code
if (isset($_GET['ajax'])){
    if(isset($_GET['newid'])){
      echo "success";
    }
    else{
      echo "fail";
    }
    exit;
}

设置一个参数以查看它是否是一个ajax请求

  $.ajax({
    type: "GET",
    url: "test.php",
    data: {newid:id, ajax: 'true'},
    dataType: 'text',
    success:function(result){
      // Test what is returned from the server
      alert(result);
    }
  });

答案 1 :(得分:0)

我认为问题在于你对这里要完成的事情或你应该如何实现这一点感到有些混乱。

尝试

if(isset($_GET['newid'])){
  // Do whatever you want when the script gets an AJAX request

  // You want to exit early to avoid having the whole page show up in the alert()
  exit;
}

// Your normal, non-AJAX PHP code goes here

请注意,您的页面将在alert()中完整返回,因为您没有提前退出,这可能是您想要为AJAX响应做的。您设置它的方式,整个页面将被发回,就像您从浏览器视口请求它一样。

相关问题