如何使用ajax将数据正确发布到div中?

时间:2014-02-10 12:22:15

标签: javascript php jquery

脚本:

function buttonBuild(id, building, nick)
  {
      $("#BuildedBox").ajax({
       type: "POST",
       url: "BlockEditor/build.php",
       data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
       cache: false,
       success: function(response)
       {
         alert("Record successfully updated");
         $.load("#BuildedBox")
       }
     });
 }

build.php:

include_once("$_SERVER[DOCUMENT_ROOT]/db.php");

$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];

echo"$block_id - $building - $nick";

的index.php:

<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a> 
<div id="BuildedBox"></div>
似乎我的剧本不起作用。我做错了什么?

3 个答案:

答案 0 :(得分:2)

检查出来

function buttonBuild(id, building, nick)
  {
      $.ajax({
       type: "POST",
       url: "BlockEditor/build.php",
       data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
       cache: false,
       success: function(response)
       {
         alert("Record successfully updated");
         /***************/
         $("#BuildedBox").html(response);
         /***************/
       }
     });
 }

答案 1 :(得分:1)

   var weightd = $("#weight").val();
              var user_id = 43;
                $.ajax({
                 type: "POST",
                url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
                data: { weight:weightd,user_ids:user_id},
                success:function(result){
                  $("#result1").html(result);

                });


<div id="result1">Result div</div>

答案 2 :(得分:0)

$.load("#BuildedBox")更改为$("#BulderBox").html(response)

当您通过ajax向脚本询问数据时,提供的数据会进入“response”变量。如果要将此数据写入div,则必须使用“.html”方法。

以这种方式更容易使用“加载”:

function buttonBuild(id, building, nick)
  {
      $("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
 }

“load”方法从服务器加载数据并将结果html写入元素:https://api.jquery.com/load/

修改

正如@ a-wolff在评论中所说,要在加载中使用POST,你应该这样构造:

function buttonBuild(id, building, nick)
  {
      $("#BuildedBox").load("BlockEditor/build.php",{
        block_id:id,
        building:building,
        nick:nick
      });
 }