dongzhiman2162 2014-04-22 17:48
浏览 33
已采纳

$ .post功能似乎没有发布

I am new to both javascript and php. I am trying to write a javascript function that will post a string back to the server so that I can capture it and save it in the database. It will eventually post data obtained from the google.maps geocoding api,but for now, I'm just trying to get ANY post to work. I have been able to post to the server with html forms, but not successfully yet using a javascript function, and I have a hunch that I am missing something basic.

I have included the jquery library in my Script.js file with: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

I have then added this function, which I pretty much just copied from the examples in my Script.js file:

<script>
function namepost(){
document.write("Tired of trying to debug this bloody thing");
$.post("test.php",{firstname:"John"});
}
</script>

For testing purposes, I have created the file test.php, and here is the code:

<?php
require_once 'Script.js';
echo "<script>namepost()</script>";
$name = $_POST['firstname'];
print_r($_POST);
echo "Firstname is {$name}";

Here is the output I get when I run the code:

Tired of trying to debug this bloody thingArray ( ) Firstname is

My function is getting called, but it doesn't appear that I am posting firstname because the $_POST gives me an empty array. I can't tell why, and I have been at this for hours and hours. Is there another file I need to include to use the jquery $.post function? Please, help me save the rest of my hair and sanity!

  • 写回答

2条回答 默认 最新

  • duane2364 2014-04-22 17:58
    关注

    The jQuery $.post will do an asynchronous POST, so your page won't be updated unless you process the results in javascript:

    $.post("test.php", {firstname:"John"}, function(result){ alert(result) });
    

    (The third parameter of $.post is a function that will execute after the server responds).

    If you want to do synchronous POST, you will need to use the jQuery $.ajax function, like this:

       $.ajax({
          type: 'POST',
          url: "test.php",
          data: {firstname:"John"},
          success: function(result){ alert(result) },
          async:false
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器