简体   繁体   English

如何将Ajax响应和HTML代码分开?

[英]How to separate ajax response and HTML code?

I have an ajax request below: 我在下面有一个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

the result is an array as such: 结果是这样的数组:

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

  more objects];

I want to use the address and block information and display them as a list of elements on my html page. 我想使用地址和阻止信息,并将其显示为html页面上的元素列表。

My concern is, I do not wish to make my ajax function too long and do my HTML coding inside the request. 我担心的是,我不希望我的ajax函数过长并且在请求中进行HTML编码。 How can I separate the DOM code (for listing the information) and the result received? 如何区分DOM代码(用于列出信息)和收到的结果? I am trying to avoid writing spaghetti code. 我试图避免编写意大利面条代码。

abstract the logic, create functions that do the tasks you want to achieve (declare them outside the ajax call) and just call them once you have the ajax response; 抽象逻辑,创建执行您要完成的任务的函数(在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)
             }

The easiest way without you having to rewrite a lot of your code is to just use functions 无需重写很多代码的最简单方法是仅使用函数

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);
  });
}

Otherwise, if you're OK/familiar with Promises, you can get a much better control over the flow of the program like this 否则,如果您确定/熟悉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);

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

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