如何使用JavaScript添加动态HTML内容(DIV)?

时间:2013-12-04 17:32:08

标签: javascript jquery html ajax

我需要帮助在从服务器端返回数据时添加动态html。我正在使用ajax / jQuery来处理服务器端处理要求。目前,ajax的成功代码部分我可以编写html元素(参见下面的 ajax ),但这对于 demo 页面是可以的,但对于实际代码,这使我写入了这些html呈现在HTML代码中。

在HTML页面中,我包含了html代码,我想在用户点击提交按钮时显示该代码并隐藏后面的视图(div id)。我可以告诉JavaScript动态添加这个HTML代码吗?从服务器端我想在

下传递以下值
<div id="package-header-message">
            <div class="spacer-vertical"></div>
            <div>Your incident was submitted on December 04, 2013 at 11:38:53 am EDT. Your test-CERT Incident ID number is: </div>
            <div class="spacer-vertical"></div>
            <div class="bold left-indent">2013-testCERTv36LBQB</div>
            <div class="spacer-vertical"></div>
          </div>  

2013-testCERTv36LBQB 我希望它根据服务器的响应进行设置。我可以在.ajax下执行此操作但我是否也可以使用javascript为我附加此值?

如果有人可以帮我定义执行流程,我将不胜感激。

HTML

<div id="frm">  
<form name="frm" method="POST" action="">
    <input type="text" name="name" id="name" value="" />
    <input type="text" name="last_name" id="last_name" value="" />
    <input type="submit" name="Update" id="update" value="Update" />
</form>
</div>  

<!-- <div id="region-content" class="grid-12 region region-content">
  <div class="region-inner region-content-inner">
    <a id="main-content"></a>
                <h1 id="page-title" class="title">Thank you for your incident submission.</h1>
                        <div id="block-system-main" class="block block-system block-main block-system-main odd block-without-title">
  <div class="block-inner clearfix">

    <div class="content clearfix">

          <div id="package-header-message">
            <div class="spacer-vertical"></div>
            <div>Your incident was submitted on December 04, 2013 at 11:38:53 am EDT. Your test-CERT Incident ID number is: </div>
            <div class="spacer-vertical"></div>
            <div class="bold left-indent">2013-testCERTv36LBQB</div>
            <div class="spacer-vertical"></div>
          </div>                       
          <p>
            The test-CERT Watch staff may contact you based on the information submitted. If you have any questions regarding this incident or would like to provide test with any edits or changes to this information, please contact test-CERT Security Operations Center at:
            </p><ul>
              <li>Phone: +1 888-282-0870</li>
              <li>Email: <a href="mailto:soc@test.com" title="Send email to the Security Operations Center Email: soc@test-cert.gov">soc@test-cert.gov</a></li>
              <li>Web: <a href="/" title="Go back to the test-CERT Homepage">http://www.test-cert.gov/</a>.</li>
            </ul>
          <p></p>
          <p>
            Secure phone and fax are available upon request. Contact test-CERT Watch at the above phone number to coordinate.
          </p>
          <p><a title="Submit another incident report" href="/forms/report">Click here</a> to submit another incident report or you can return to the <a href="/" title="Go back to the test-CERT Homepage">test-CERT Homepage</a>.
          </p>
              </div>
  </div>
</div>      </div>
</div>-->

AJAX / jquery的

  $("#update").click(function (e) {
        e.preventDefault();
        var name = $("#name").val();
        var last_name = $("#last_name").val();
        var dataString = 'name=' + name + '&last_name=' + last_name; 
alert(dataString);
        $.ajax({  
  type: "POST",  
  url: "bin/process.php",  
  data: dataString,  

   success: function(data) {  
      alert("ff");
  // var ctrlArray = data.split('&'); 
 if(result.indexOf("pass") > -1)      
//alert("ff");
    $('#frm').html("<div id='message'></div>");  
    $('#message').html("<h2>Contact Form Submitted!</h2>")  
    .append("<p>We will be in touch soon.</p>")  
    .hide()  
    .fadeIn(1500, function() {  
      $('#message').append("<img id='checkmark' src='images/check.png' />");  
    });  
  }  
});  
return false;

  })

DEMO

2 个答案:

答案 0 :(得分:0)

为什么不将你想要显示的html的静态部分提交到那里(或者可能在单独的模板.html文件中),但是隐藏,只是填充你的请求成功获得的数据。然后你可以取消隐藏它。

$('.left-indent').text(data.value); //where data.value, say, equals "2013-testCERTv36LBQB"
$(#package-header-message').show();

答案 1 :(得分:0)

设置并从服务器返回日期也是明智之举,因此您可以在事情发生时获得一个中央权限。以毫秒为单位打包为UTC通常是一个好主意,因为这为客户端开发人员提供了很多选项,并且在时区等方面更容易管理。所以,假设你已经将以下JSON交给了客户端:

{
    responseDate:1386181171730,
    userId:'2013-testCERTv36LBQB'
}

以下是我通常使用{{}}处理HTML格式来标记化替换变量的方法。

function createPhm(ajaxSuccessObject){

    var //var block

    phm =[ //array/whitespace format so we can still view/edit in an HTML-ish format
        '<div id="package-header-message">',

            '<p>Your incident was submitted on {{DATE}}. Your test-CERT Incident ID number is:</p>',

            '<span class="bold left-indent">{{USER_ID}}</span>',

         '</div>'

    ].join(''), //converted to string

    injectedValues = {
        DATE = Date( ajaxSuccessObject.date ),
        USER_ID = ajaxSuccessObject.userId
    }

    ;//end var block



    return ( injectValues( injectedValues, phm ) );
}

//broke this out for more generic handling of HTML
function injectValues(valuesObj, targetString){
    for(var x in valuesObj){

        var globalRegExMatcher = new RegExp('\\{\\{'+ x +'\\}\\}','g');

        targetString = targetString.replace( globalRegExMatcher, valuesObj[x] );
    }

    return targetString;
}

所以你的ajax成功函数可能如下:

...
    success: function(jsonObj){
        $( createPhm(jsonObj) ).appendTo('#frm'); //or prependTo for putting at top
    },
...

快速注意:不要像以前一样使用.html。这取代了容器中的所有html。它只是innerHTML。

此外,如果您的HTML永远不会更改,请将其放入HTML文件中。我通常只在我的HTML文件中有一个空<div id="package-header-message"></div>而在.html中直接进入该文件,但希望保持html类似以避免混淆。