简体   繁体   English

使用Jquery从JSON生成多个HTML元素?

[英]Generate multiple HTML elements from JSON using Jquery?

How to use Jquery and Javascript to extract JSON from $ajax and then do a foreach, and create a string that will append to html DOM? 如何使用Jquery和Javascript从$ ajax中提取JSON,然后执行foreach,并创建将附加到html DOM的字符串?

Something like: 就像是:

$(document).ready(function (e) {

$.ajax({
    type: "POST",
    url: "Companies/GetSearchRatios",
    context: this,
    success: function (data) {
       //return JSON
    }
});

Result JSON 结果JSON

[{"name":"MyNAme","value":350},{"name":"Hello","value":356}]

I can easily acces this values inside $ ajax method success, but how can I extract this value outside of method and use it to append to DOM? 我可以轻松地在$ ajax方法成功内访问此值,但是如何在方法之外提取该值并将其附加到DOM?

This is what I need as a result of some for/foreach method: 由于某些for / foreach方法,这就是我需要的:

  var $gElemRatios =
    '<option value=""></option>' +
    '<option value="350">MyNAme</option>' +
    '<option value="356">Hello</option>';

Then I use this var to combine with another: 然后,我使用此var与另一个变量组合:

 var $gElem =
    '<div class="cbox cboxQuarterWidth">' +
         '<select id="combobox_0">' +
               $gElemRatios + // here I add previous generated elem
         '</select>' +
    '</div>';

And finally: 最后:

$("#main").append($gElem);

Any ideas? 有任何想法吗?

You can use $.each to loop through the data passed to the success handler: 您可以使用$.each遍历传递给成功处理程序的数据:

$.ajax({
    type: "POST",
    url: "Companies/GetSearchRatios",
    context: this,
    success: function (data) {
       $.each(data,function(){
          console.log(this.name); //just an example how to access things
          $('#select').text(this.value); //maybe?
       });
    }
});

See this fiddle 看到这个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM