I have a pretty specific one here. I'm basically Trying to post an array of strings to one of my ruby servers and process it back to objects. Problem is when I send across the Json it comes out like this
Its pretty bizarre syntax that's coming back to the server.
So my question is where does my error lie and how do i fix it?
1:Is it my ruby/rails server not parsing json back correctly? (I doubt it as the json looks mangled anyway)
2: Is it the way I've constructed my array?
3:Or is it (most likely) How I'm posting my array?
So just to give a little more detail. On the client side in the javascript I have your everyday array of strings. When I run this:
JAVASCRIPT ARRAY:
var $arrayToSend = JSON.stringify(headersTitleArr);
console.log($arrayToSend);
It produces:
[" Page Title "," Description "," Keywords "," Internal Links ","
External Links "," Content files "," Notes "]
After my post method which is listed as such:
JAVASCRIPT POST:
$.ajax({
type: 'POST',
url: webAppURL+websiteID+".json",
data: {elementTypes:$开发者_Go百科arrayToSend},
success: function(){
console.log("YIPPEE I HAS A SUCCESS");},
dataType: 'json'
});
On the ruby side, this is what comes up after dumping params as such:
Ruby code as requested.
RUBY:
puts YAML::dump(params[:elementTypes])
@x = (params[:elementTypes])
@elementTypes = JSON.parse(@x)
and the printed result on server:
--- "[\" Page Title \",\" Description \",\" Keywords \",\" Internal
Links \",\" External Links \",\" Content files \",\" Notes \"]"
You are mixing types. Don't stringify anything, or stringify everything. In your case I would replace:
$.ajax({
type: 'POST',
url: webAppURL+websiteID+".json",
data: {elementTypes: JSON.stringify($arrayToSend)},
success: function(){
console.log("YIPPEE I HAS A SUCCESS");},
dataType: 'json'
});
with
$.ajax({
type: 'POST',
url: webAppURL+websiteID+".json",
data: {elementTypes: headersTitleArr},
success: function(){
console.log("YIPPEE I HAS A SUCCESS");},
dataType: 'json'
});
jQuery will handle the stringify-ing for you. If you want to use stringify:
$.ajax({
type: 'POST',
url: webAppURL+websiteID+".json",
data: JSON.stringify({elementTypes: headersTitleArr}),
success: function(){
console.log("YIPPEE I HAS A SUCCESS");},
dataType: 'json'
});
You have to either send a javascript object, or a string representing JSON. But mixing the two will result in badly formed data.
精彩评论