从jQuery GET请求返回HTML

时间:2013-06-16 18:55:27

标签: php javascript jquery html json

我正在尝试从jQuery触发的GET请求中返回HTML表单,但我不确定如何执行此操作。客户的服务器将调用我的服务器,然后返回一个表单。我理解相同的域策略发挥作用,并且有一些方法,如JSONP,但我无法弄清楚如何返回整个HTML表单。

现在我正在测试localhost,所以我可以在我的服务器上使用GET到另一个页面而不必担心相同的域策略,如果这有助于简化事情

这是我的思考过程。

//form_deliver.php
//this code would go on the customer's server which would then call to mine
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<?php
    echo "look at all of this stuff!";
?>
<script> 
    $.getJSON("/form_deliverer.php?form_request=true",function(data) {
            //alert(data.check); //this was just for testing, 
    });
</script>

这是将GET请求发送到

的页面
//form_deliverer.php
//this code is on my server which will return a form to the customer
<?
if(isset($_GET['form_request'])){
   // echo json_encode(array("check" => "true")); //just for testing
    //return form here
?>

为简单起见,我们假设这是我想要返回的形式

<form method="post">
    <input type="textbox" name="text"/>
    <input type="submit" name="submit_text"/>
</form>

根据jackJoe的建议编辑这是我的更新

form_deliver.php上的代码

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<?php
    echo "look at all of this stuff";
?>
<script> 
    var form_request = "true";
    $.get("/form_deliverer.php", {var: form_request},
        function(data){
        $("#yourdiv").html(data);
    }, "html");
</script>
<div id = "yourdiv">

</div>

这是在form_deliverer.php

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

?>

2 个答案:

答案 0 :(得分:2)

正如我在评论中所说,您可以使用AJAX或在您的情况下使用GEThttp://api.jquery.com/jQuery.get/),它可以让您返回html。

示例:

$.get("yourPHP.php", {var: somethingdynamicpassedviajavascript},
     function(data){
     //get the result
     $("#yourdiv").html(data);
}, "html");

此函数的结尾具有返回类型(在本例中为“html”)。此示例将HTML放入div #yourdiv

答案 1 :(得分:1)

如果您最终使用JSONP,则必须使表单标记为字符串,该字符串应该是服务器响应的json编码对象的属性值。

所以,你的服务器必须回复这样的事情:

<?php
$o = new stdClass();
$o->formHTML = '<form>...</form>';
echo json_encode($o);
?>
相关问题