1

当我使用脚本使用 ajax 从特定 url 获取内容时,不显示我的 HTML 内容,即不显示我的表格元素:我从特定 url 获取数据并将其显示在警报框中,并且还document.write用于在页面上写入来自我调用的 url 的数据:

<head>
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />
  <script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js"></script>
  <script type="text/javascript">
  $(document).ready(function() {
    $.ajax({
      type:"POST",
      url:"http://your url",
      success: onSuccess,
      error:onError
    });
  });
  function onSuccess(data){
    var servertext=data;
    document.write(servertext);
    alert(servertext);
  }
  function onError(data){
    alert(data+'error');
  }
  </script>
</head>
<body>
  <p> hello</p>
  <table height="150px" weight="150px" border="1px">
  <tr>
    <td><img src="green.png" height="100px" width="100px" /></td>
  </tr>
</table>

enter code here

4

3 回答 3

5

document.write页面完成加载后不应使用。如果你调用它,它会隐式调用document.open,这会使页面空白并创建一个新文档。

于 2012-06-05T11:15:50.967 回答
1

如果你servertext是 html,那么试试这个:

<script type="text/javascript">
    $(document).ready(function() {
            $.ajax({
                type:"POST",
                url:"http://your url",
                success: onSuccess,        
                error:onError                   
            });          
    });
    function onSuccess(data){
        var servertext=data;

        $("div#ajaxContent").html(servertext);

        alert(servertext);
    }
    function onError(data){
    alert(data+'error');

    }       
</script>
</head>
<body>
<p> heloo</p>
     <table height="150px" weight="150px" border="1px">     
        <tr>
            <td> <img src="green.png" height="100px" width="100px" /></td>
        </tr>
    </table>
    <div id="ajaxContent"></div>
</body>
于 2012-06-05T11:17:57.100 回答
0

不要使用document.write,因为它不会起作用并且是错误的。

相反,向您的 HTML 添加一些占位符元素,然后分配响应:

document.getElementById("myplaceholder").innerHTML = servertext;

这会将响应放入定义为的元素中:

<div id="myplaceholder"></div>

另请注意,您只能将请求发送到与包含 AJAX 代码的页面位于同一域下的页面。(同源政策

于 2012-06-05T11:16:25.997 回答