【问题标题】:How to separate ajax response and HTML code?如何分离 ajax 响应和 HTML 代码?
【发布时间】:2016-09-21 07:28:02
【问题描述】:

我在下面有一个 ajax 请求:

    $.ajax({
            url: "/geodata",
            data: {'lat':lat,'lng':lng},
            type: "POST",
            success: function(result) {
                if ( typeof result == "string") {
                    console.log("helo");
                 } else {
                 // do things with the result here

结果是一个数组:

arr = [{address: '1300 BRYANT ST',
  block: '3903',
  cnn: '517000',
  latitude: '37.7690871267671',
  longitude: '-122.411527667132',
  received: '2016-05-06' }, 

  more objects];

我想使用地址和块信息并将它们显示为我的 html 页面上的元素列表。

我担心的是,我不想让我的 ajax 函数太长并且在请求中进行 HTML 编码。如何分离 DOM 代码(用于列出信息)和收到的结果?我试图避免编写意大利面条式代码。

【问题讨论】:

    标签: javascript jquery html ajax


    【解决方案1】:

    无需重写大量代码的最简单方法就是使用函数

    function getLocations(lat, lng) {
      let req = $.post('/geodata', {lat: lat, lng: lng});
      req.done(function(result) { renderLocations(result); });
      req.fail(function(jqxhr, textStatus, err) { console.error(err); });
      return req;
    }
    
    function renderLocations(locations) {
      locations.foreach(function(location) {
        // render location node
        // <div class="location">
        //   <p>{location.address}</p>
        //   <p>{location.lat} {location.lng}</p>
        // </div>
        $('#locations').append(childNode);
      });
    }
    

    否则,如果你对 Promises 没问题/熟悉,你可以像这样更好地控制程序的流程

    function getLocations(lat, lng) {
      return new Promise(function(resolve, reject) {
        let req = $.post('/geodata', {lat: lat, lng: lng});
        req.done(function(data, textStatus, req) { resolve(data); });
        req.fail(function(req, textStatus, err) { reject(err); });
      });
    }
    
    function renderLocations(parentNode) {
      return function(locations) {
        locations.foreach(function(location) {
          // render location node
          // <div class="location">
          //   <p>{location.address}</p>
          //   <p>{location.lat} {location.lng}</p>
          // </div>
          parentNode.append(childNode);
        });
      };
    }
    
    function logError(err) {
      console.error('an error occurred:', err.message);
    }
    
    // put them together
    getLocations(37, -122).then(renderLocations($('#locations')), logError);
    

    【讨论】:

    • 使用原生 Promise 比 jQuery ajax 方法返回的 Promise 有优势吗?
    • 如果你想要我的意见,一个是原生垃圾,另一个是第三方垃圾。与 3rd 方专有的东西相比,我发现更容易合理地投资时间学习本地人。 JavaScript Promise 是我们得到的,所以你不妨了解一下:s
    • 你觉得这两个实现有什么不足?是否有任何您认为可以接受的库(节点、角度等)?
    • 这里有更多关于JS Promises vs jQuery Deferreds的信息。我个人对 JS Promise 的问题是他们急切且过于复杂。请参阅 folktale/data.task 了解惰性承诺,这些承诺是如此简单,您可能自己也可以编写它——并且几乎拥有任何其他更复杂的实现所提供的所有功能——然后是一些。
    【解决方案2】:

    抽象逻辑,创建执行您想要完成的任务的函数(在 ajax 调用之外声明它们)并在获得 ajax 响应后调用它们;

    function insertDataInDom(data){
        document.getElementById("data1").innerHTML = data.block
        document.getElementById("data2").innerHTML = data.address
    }
    
    $.ajax({
            url: "/geodata",
            data: {'lat':lat,'lng':lng},
            type: "POST",
            success: function(result) {
                if ( typeof result == "string") {
                    console.log("helo");
                 } else {
                   insertDataInDom(result.data)
                 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2013-04-21
      • 2012-07-31
      • 1970-01-01
      • 2013-04-02
      • 2012-03-02
      • 1970-01-01
      相关资源
      最近更新 更多