Required JSON parameter is not present in jQuery D

2019-09-08 06:04发布

I am submitting my array from jQuery Datatables for server side processing, in the following form

Creating the array

var testArr = [];  
testArr.push('A')

and under the $('#form').submit function

$.ajax({
    url: 'run',  
    data: testArr,  
    dataType :"json",  
    success: function(testArr){  
        alert( "Data Saved: " + testArr); 
    }  
});`

And on the Spring Controller side , my annotation looks like this

@RequestMapping(value="/run", method=RequestMethod.POST,
                headers="Accept=application/json")  
public String run(@RequestParam("testArr") JSON testArr) {

When I submit the data for server side processing , it throws me an error stating that

Required JSON parameter 'testArr' is not present

I am unable to understand what am I doing wrong. Please help.

3条回答
我命由我不由天
2楼-- · 2019-09-08 06:31

jSon and jSonP are pairs. You are not sending a pair. For test purposes, try testArr.push("{'A':'a'}")

ps: I am a novice!

查看更多
贼婆χ
3楼-- · 2019-09-08 06:32

I think testArr needs to be a json object: try using data: { 'testArr': testArr }

查看更多
倾城 Initia
4楼-- · 2019-09-08 06:35

[edit: I didn't really provide a complete answer, but some of this might be useful so I'll leave it around]

Assuming that you've confirmed testArr is JSON, I would say that it's because you're trying to alert a JSON object as a string, which you can't do. I imagine you can parse it before trying to alert it if that's what you want to do. For the purpose of testing, if you console.log it, you will also be able to inspect what's being "alerted" better.

For maintainability and understandability's sake, I wouldn't use the same name for the object being passed into "success" since it might not relate to your original JavaScript variable at all. I understand that you were providing reduced sample code, but just sayin'.

success: function(data) {
  returned = $.parseJSON(data);
  console.log("Data Saved: " + returned);
}

Thanks to another response I looked a bit more carefully. [ 'A' ] is not in fact valid JSON. That doesn't mean it won't try to submit, but I have to admit I ignored the server side of things; smarter people than me will be able to help you identify if it's returning valid JSON. (hint: if it's just returning what you sent, it's not)

查看更多
登录 后发表回答