donglan7594 2017-09-28 17:33
浏览 79

如何使用Jquery AJAX获取POST数据

I am trying to POST simple data using AJAX. My HTML code is

<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">

My JQuery code is

$('#mybtn-1').click(function(){

    var newSweet = $('#sweet').val();
    if($.trim(newSweet) !== '')
   {
    $.ajax({
        url:"../test_chat.php",
        method:"POST",
        data:{sweet:newSweet},
        dataType:"text",
        success:function(data){
            $('#test_wrap').load("../test_chat.php").fadeIn("slow");
            alert('Success');
        }
    });
   }
});

And my test_chat.php code is

<?php 
    echo $_POST["sweet"];
    echo 'hello';
?>

I want to echo the POST data in a div with name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.

I know its happening because the load function is reloading the php file but I am looking for a solution so that I can show the POST data on my page.

Thanks

  • 写回答

3条回答 默认 最新

  • dongluanguang4774 2017-09-28 17:36
    关注

    You don't need to echo it with PHP, you can display it directly from the jQuery success callback:

    $.ajax({
        url: "../test_chat.php",
        method: "POST",
        data:{
            sweet: newSweet
        },
        success: function(data) {
            $('#test_wrap').load("../test_chat.php").fadeIn("slow");
    
            if (data !== null && data !== undefined) {
                alert('Success');
    
                // Here "data" is whatever is returned from your POST
                $("#some_content").html(data);
            }
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题