将Ajax调用合并到一个脚本标签中

时间:2019-02-04 18:51:43

标签: javascript jquery ajax

我仍处于学习过程中,很想知道如何将下面的两个脚本结合起来,我的代码现在运行良好,但是我想将其最小化并结合起来。

以下是两个脚本中的两个区别:
&$filter=substringof('Consumer Products',Line1)",
$("#boxWrap").append(

<script type="text/JavaScript">
$(document).ready(function(){
$.ajax({
    url:  "/NewBusiness/_api/web/lists/GetByTitle('CompletedSubmissionTiles')/Items?$select=EncodedAbsUrl,Title,Line1,Line2,Hyperlink,TargetWindow,DescriptionHTMLOption,Line1,Line2,Line3,Line4,Line5,Line6,Line7,Line8,TileOrder&$orderby=TileOrder asc,Title asc&$filter=substringof('Healthcare',Line1)",
    type: "GET",
    headers: {
        "accept": "application/json; odata=verbose"
    },
    success: function (data) {
    if (data.d.results) {
    var object = data.d.results;
    var TileDesc;
    var Line1var;
    var Line2var;
    var Line3var;
    var Line4var;
    var Line5var;
    var Line6var;
    var Line7var;
    var Line8var;
    var Line9var;
    var Line10var;

    for(var i = 0; i < object.length; i++)
    {
    
    if(object[i].DescriptionHTMLOption != null) { // Covers 'undefined' as well
        TileDesc = "<div class='TileDescr'>" + object[i].DescriptionHTMLOption + "</div>";
    } else {
        TileDesc = "";
    }
    
    if(object[i].Line1 != null) { // Covers 'undefined' as well
        Line1var = "<div class='Line1'>" + object[i].Line1 + "</div>";
    } else {
        Line1var = "";
    }
    
    $("#boxWrap").append("<div class='col-md-4 box' data-toggle='modal' data-target='#modal"+object[i].TileOrder+"' id='TileBox"+object[i].TileOrder+"'><div id='titleBox' class='titleBox'><h1>" + object[i].Title + "</h1><div style='width:250px; height: 130px;background-color: white; border: 1px solid lightgrey;'><img style='width: auto; height: inherit; padding-left: 10px;' src='" +  object[i].EncodedAbsUrl + "' alt='" + object[i].Title +"'/></div></div></div>");
    }
    }
    }									
    })				
});
</script>

<script type="text/JavaScript">
$(document).ready(function(){
$.ajax({
    url:  "/NewBusiness/_api/web/lists/GetByTitle('CompletedSubmissionTiles')/Items?$select=EncodedAbsUrl,Title,Line1,Line2,Hyperlink,TargetWindow,DescriptionHTMLOption,Line1,Line2,Line3,Line4,Line5,Line6,Line7,Line8,TileOrder&$orderby=TileOrder asc,Title asc&$filter=substringof('Consumer Products',Line1)",
    type: "GET",
    headers: {
        "accept": "application/json; odata=verbose"
    },
    success: function (data) {
    if (data.d.results) {
    var object = data.d.results;
    var TileDesc;
    var Line1var;
    var Line2var;
    var Line3var;
    var Line4var;
    var Line5var;
    var Line6var;
    var Line7var;
    var Line8var;
    var Line9var;
    var Line10var;

    for(var i = 0; i < object.length; i++)
    {
    
    if(object[i].DescriptionHTMLOption != null) { // Covers 'undefined' as well
        TileDesc = "<div class='TileDescr'>" + object[i].DescriptionHTMLOption + "</div>";
    } else {
        TileDesc = "";
    }
    
    if(object[i].Line1 != null) { // Covers 'undefined' as well
        Line1var = "<div class='Line1'>" + object[i].Line1 + "</div>";
    } else {
        Line1var = "";
    }
    
    $("#boxWrap2").append("<div class='col-md-4 box' data-toggle='modal' data-target='#modal"+object[i].TileOrder+"' id='TileBox"+object[i].TileOrder+"'><div class='titleBox'><h1>" + object[i].Title + "</h1><div style='width:250px; height: 130px;background-color: white; border: 1px solid lightgrey;'><img style='width: auto; height: inherit; padding-left: 10px;' src='" +  object[i].EncodedAbsUrl + "' alt='" + object[i].Title +"'/></div></div></div>");
    }
    }
    }									
    })	
});
</script>

3 个答案:

答案 0 :(得分:1)

由于filterid是这里唯一的变量,因此您可以创建一个单独的函数,该函数接受这2个参数并在其中进行ajax调用。将filter附加到URL的末尾。在选择器id中使用$(id).append,然后创建具有2个属性的对象数组。为数组中的每个项目调用通用ajax函数:

function getDataFromAjax(filter, id) {
   $.ajax({
      // append "filter" to the end of url
      url: "/NewBusiness/_api/web/lists/....Title asc&$filter=" + filter,
      type: "GET",
      headers: {
         "accept": "application/json; odata=verbose"
      },
      success: function(data) {
         if (data.d.results) {
            var object = data.d.results;
            var TileDesc;
            // OTHER VARIABLES

            for (var i = 0; i < object.length; i++) {
               /*
                LOTS OF LOGIC
               */

               // get the dynamic id
               $("#" + id).append("<div class='col-md-4 box' and so on");
            }
         }
      }
   })
}

var array = [{
      filter: "substringof('Healthcare',Line1)",
      id: "boxWrap"
   },
   {
      filter: "substringof('Consumer Products',Line1)",
      id: "boxWrap2"
   }
]

array.forEach(i => getDataFromAjax(i.filter, i.id))

答案 1 :(得分:0)

您不必做很多事,

<script>
    $(document).ready(function(){
        getConsumerProducts();
        getHealthcare();
    });

    function getConsumerProducts(){
        $.ajax({
            // your many many lines of code
            // ...
        )}
    }
    function getHealthcare(){
        $.ajax({
            // your many many lines of code
            // ...
        )}
    }
</script>

答案 2 :(得分:0)

我建议使它成为它自己的函数,该函数接受元素id,该元素id将接收附加信息和过滤器,如下所示:

import Vue from "nativescript-vue";
import Vuex from 'vuex'
import store from './store/store';
import * as applicationSettings from 'tns-core-modules/application-settings'

import router from './router'

Vue.prototype.$router = router


Vue.config.silent = false
Vue.use(Vuex)

new Vue({
    render: h => h('frame', [h(router['login'])]),  store

}).$start()

然后,您可以调用此函数x次,分别将每个过滤器和元素ID分别传递给该函数。因此,您可以将其放入function DoMyApiCalls(elementId, filter){ .ajax({ //Inside here append your parameters into your strings, url: url: "/NewBusiness/_api/web/lists/GetByTitle('CompletedSubmissionTiles')/Items?$select=EncodedAbsUrl,Title,Line1,Line2,Hyperlink,TargetWindow,DescriptionHTMLOption,Line1,Line2,Line3,Line4,Line5,Line6,Line7,Line8,TileOrder&$orderby=TileOrder asc,Title asc&$filter=" + filter, type: "GET", //etc. success:function(data){ //etc. //Append to passed in element id $('#' + elementId).append(); } }); }

document.ready