在Javascript

时间:2016-03-14 08:05:43

标签: javascript jquery json ajax jsp

伙计们,我知道它的虚拟问题,但我花了好几个小时,并且无法达到..我试图通过另一个JS文件中的AJAX调用将JSON数组传递给JSP。它给了我一个404错误。任何帮助,将不胜感激。这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

您需要有一个有效的网址才能将值发送到后端:

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