JSON编码值未正确返回

时间:2013-06-16 23:07:10

标签: php jquery html ajax json

我正在尝试从我的服务器调用一个文件并返回一个HTML表单。我问了一个问题here,但是现在我又遇到了另一个问题。

显示文本框和提交按钮,但由于数据是JSON编码并通过AJAX返回到DIV,我不太确定如何处理它。

现在这是结果。我有“文本框和提交按钮”的地方,那些元素实际上就在那里。其他文字出现在它周围。

testing
{"formHTML":"
"textbox here" " submit button here"<\/form>"}

这是在另一台调用我的服务器上的代码。这是显示

的页面
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<?php
    echo "testing";
?>
<script>
$.ajax({
        type: 'GET',
        url: 'form_deliverer.php',
        data: "true",
        success: function(response) { // on success..
            $('#yourdiv').html(response); // update the DIV
        }
    })
</script>
<div id = "yourdiv">
//form is displayed here
</div>

这是被调用的页面,form_deliverer.php

<?
$o = new stdClass();
$o->formHTML = "<form method='post'><input type='textbox' name='text'/><input type='submit' name='submit_text'/></form>";
echo json_encode($o);
?>

因为AJAX会自动更新div,我该如何解码数据呢?我应该这样做吗?

作为参考,这会在没有额外文本的情况下正确显示表单。但是,由于我将从另一台服务器调用并且必须处理相同的域问题,我将不得不使用JSONP

<?
if(isset($_GET['true'])){
    echo "
    <form method='post'>
        <input type='textbox' name='text'/>
        <input type='submit' name='submit_text'/>
    </form>
    ";
}
?>

1 个答案:

答案 0 :(得分:0)

您不需要解码数据,但您必须将响应视为对象。因为你json_encode()编了一个stdClass,你的ajax调用基本上会得到这样的东西作为回报:

{"formHTML": "<form method='post'><input type='textbox' name='text'/><input type='submit' name='submit_text'/></form>"}

要访问该字符串,您只需编写

即可
$("#yourdiv").html(response.formHTML);

但是,如果您只传入字符串,则可以简单地json_encode()字符串而不是创建对象然后对其进行编码。这样,您就可以直接在javascript中使用response

form_deliverer.php

<?
echo json_encode("<form method='post'><input type='textbox' name='text'/><input type='submit' name='submit_text'/></form>");
?>

的javascript

$.ajax({
        type: 'GET',
        url: 'form_deliverer.php',
        data: "true",
        success: function(response) { // on success..
            $('#yourdiv').html(response); // update the DIV
        }
    })