duanbiyi7319 2016-01-11 23:11 采纳率: 100%
浏览 9
已采纳

Ajax和PHP同页不起作用

I am trying to send a JSON object via ajax to the same page. While running my code, the ajax function does seem to send the data, as I can see on the response, that the $id in the PHP code, is changed to 200, but I am unable to display it on the webpage. I have included the jquery.js file (I'm not sure if I need to add another js library or not). I tried looking at a lot of stackoverflow answers but was unable to solve my problem. Any help would be appreciated.

PHP Code:

   <?php
        if(isset($_POST['area_id'])){
            $id = $_POST['area_id'];
            echo "Area ID: ".$id;
        } else {
            echo "test";
        }
    ?>

JQuery AJAX

var dat = {area_id: 200, title: 'title'};
$.ajax({
    type:"POST",
    data: dat,
    success:function(res){
        alert(res);
    }
});
  • 写回答

3条回答 默认 最新

  • doumu1951 2016-01-11 23:21
    关注

    [based on comments to the question...]

    Your page isn't being updated because you've written no code to update it. echo simply emits text to the output, and alert() simply displays text to the user in a message box. In order to update the page client-side you'll need to write code which does that.

    For example, if you have an element with id="output" and want to set the response text to that element, you'd do this:

    $('#output').text(res);
    

    That element would then get that text:

    <div id="output">Area ID: 200</div>
    

    Server-side code has no way of altering a page that's already been sent to the browser. When your client-side code receives new data via AJAX, that client-side code needs to use that data in whatever way you want it to.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?