【问题标题】:Ajax, using div tags to set javascript valuesAjax,使用 div 标签设置 javascript 值
【发布时间】:2012-02-17 18:10:53
【问题描述】:

我可以使用 ajax 轻松设置 div 标签。但是我想使用 ajax 设置 javascript 值。我曾尝试使用javaScriptVariable = div.innerHTML 读取 div 标签,但它显示为空白。

有人可以帮忙吗?提前致谢。

<html>
<head>
<title>Log In</title>

<!-- script tag for ajax jquery -->
<link href='style.css' type="text/css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function()

              {
              //Get Data ajax function 
              $.post(
                     'getData.php',
                     {

                     },                                           
                     function(response)
                     {
                     $('#name').html($('#1' , response).html());
                     $('#sname').html($('#2' , response).html());                                           
                     })
              return false;
              })

var x;
x = name.innerHTML;
document.write(x);

</script>

</head>

<body>

【问题讨论】:

  • 您似乎也没有名为 #name#sname 的元素。请记住,Ajax 是异步的。

标签: javascript ajax html tags


【解决方案1】:

如果不给jquery的html()方法传值,它会返回当前值:

var x = $('#name').html();
document.write(x);

【讨论】:

  • 这覆盖了其他 HTML 元素。它可以工作,但所有其他 HMTL 元素都被掩盖了。你能帮忙阻止这一切吗?
  • 在您的示例中,您在 head 标签中使用了 document.write ......这可能会导致各种问题。但是,如果它在您的身体中,那么这是 CSS 问题,而不是 JS 问题。
【解决方案2】:

这是因为这两行代码在脚本加载后立即执行。我假设此时该元素可能为空。

x = name.innerHTML;
document.write(x);

当 ajax 调用返回时,您需要设置 x

$(document).ready(function()
{
    //Get Data ajax function 
    $.post(
        'getData.php',
        {

        },                                           
        function(response)
        {
            $('#name').html($('#1' , response).html());
            $('#sname').html($('#2' , response).html());

            var x = $('#name').html();
            document.write(x);
        })
    return false;
});

【讨论】:

  • 非常感谢!我花了一天的时间哈哈
  • 这覆盖了其他 HTML 元素。它可以工作,但所有其他 HMTL 元素都被掩盖了。你能帮忙阻止这一切吗?
【解决方案3】:

您遇到了问题,因为您没有在任何地方定义变量 name

为什么还要麻烦通过 div 呢?直接去var:

var x;
// ...

                 function(response)
                 {
                 $('#name').html($('#1' , response).html());
                 $('#sname').html($('#2' , response).html());
                 //this will set x, you can do this instead of, or in addition to the above
                 x = $('#1' , response).html();
                 })

【讨论】:

    猜你喜欢
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多