简体   繁体   English

将json数组传递给Javascript中的ajax调用

[英]passing json array to ajax call in Javascript

guys i know its dummy questions but i spent hours on this and cant reach .. I am trying to pass a JSON array to JSP via an AJAX call in another JS file.伙计们,我知道它的愚蠢问题,但我在这个问题上花了几个小时却无法解决..我试图通过另一个 JS 文件中的 AJAX 调用将 JSON 数组传递给 JSP。 It is giving me a 404 error.它给了我一个 404 错误。 Any help would be appreciated.任何帮助,将不胜感激。 Here is my code:这是我的代码:

function GridLibrary(fileName) {
    this.fileName = fileName;
}

GridLibrary.prototype = {
    setFileName : function(fileName) {
        this.fileName = fileName;
    },
    getFileName : function() {
        return this.fileName;
    }
};

GridLibrary.prototype.display = function() {
    $.ajax({
        url : this.getFileName(),
        dataType: "json",
        error : function(that, e) {
            console.log(e);
        },
        success : function(data) {
            alert("found");
        }
    });
};
var Json = [{
    "id": 1,
    "name": "name1",
    "age" : 10,
    "feedback": "feedback1"
}, {
    "id": 2,
    "name": "name2",
    "age" : 90,
    "feedback": "feedback2"
}, {
    "id": 3,
    "name": "name3",
    "age" : 30,
    "feedback": "feedback3"
}, {
    "id": 4,
    "name": "name4",
    "age" : 50,
    "feedback": "feedback4"
}];

new GridLibrary(Json).display();

You need to have a valid url to send the values to the backend:您需要有一个有效的 url 才能将值发送到后端:

function GridLibrary(url, data) {
  this.url = url;
  this.data = data;
}

GridLibrary.prototype = {
  setData: function(data) {
    this.data = data;
  },
  getData: function() {
    return this.data;
  },
  setUrl:function(url){ this.url = url; },
  getUrl:function(){ return this.url; },

  display : function() {
    $.ajax({
      url: this.getUrl, // <----the url where you want to send the data
      data:this.getData, //<----should be the array data
      dataType: "json",
      contentType:"application/json", // <----add this contentType
      error: function(that, e) {
        console.log(e);
      },
      success: function(data) {
        alert("found");
      }
    });
  }
};

var url = '/url/to/send',
    data = [{}....];

new GridLibrary(url, data).display();

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

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