function getvalue1(){
debugger
var str=document.getElementById("SystemName").value;
var str1=document.getElementById("IP").value;
var str2=document.getElementById("SystemLevel").value;
var str3=document.getElementById("Ownera").value;
var str4=document.getElementById("Ownerb").value;
var str5=document.getElementById("SystemDesc").value;
var str6=document.getElementById("SystemDate").value;
var str7=document.getElementById("Recorder").value;
$.ajax({
type:"post",
url:"../AddServlet",
data: {
str:str,
str1:str1,
str2:str2,
str3:str3,
str4:str4,
str5:str5,
str6:str6,
str7:str7
},
async:false,
dataType:"json",
contentType:"application/json;charset=utf-8",
success:function (data) {
$.message.alert('successful');
},
error:function () {
alert("failedjump");
}
});
}
The previous is my js code, I wanna to take these "strs" into the servlet, I programmed servlet part to get the data is
enter image description here
But these strings are null in the servlet. How can I get the JSON data? thx!
getParameter will read standard form encoded data, not JSON data.
This wouldn't normally be a problem because you are sending standard form encoded data, not JSON.
However, since you have said contentType:"application/json;charset=utf-8", you are claiming to be sending JSON, so it isn't being parsed.
Remove that line.
Despite from the AngularJS documentation for angular.fromJson being spectacular, I still don't know how to use it to its fullest potential. Originally I have just been directly assigning the JSON data response from an HTTP request to a $scope variable. I've recently noticed that Angular has a built-in fromJson() function, which seems like something I'd want to use. If I use it, is it safer and can I access data elements easier?
This is how I've been doing it:
$http({
method: 'GET',
url: 'https://www.reddit.com/r/2007scape.json'
}).then(function success(response) {
var mainPost = response; // assigning JSON data here
return mainPost;
}, function error(response) {
console.log("No response");
});
This is how I could be doing it:
$http({
method: 'GET',
url: 'https://www.reddit.com/r/2007scape.json'
}).then(function success(response) {
var json = angular.fromJson(response); // assigning JSON data here
return json;
}, function error(response) {
console.log("No response");
});
It is pointless to convert the response to json as angular does it for you. From angular documentation of $http:
Angular provides the following default transformations:
Request transformations ($httpProvider.defaults.transformRequest and $http.defaults.transformRequest):
If the data property of the request configuration object contains an object, serialize it into JSON format.
Response transformations ($httpProvider.defaults.transformResponse and $http.defaults.transformResponse):
If XSRF prefix is detected, strip it (see Security Considerations section below).
If JSON response is detected, deserialize it using a JSON parser.
I'm using VS2012, and running an ASP.NET MVC4 project.
I cannot seem to get this to fire below :
$.ajax({
url: "~/xml/JsonTest.json",
type: "GET",
dataType: "json",
success: function (json) {
alert("HI");
}
});
I also tried it this way , but to no avail :
$.getJSON('../xml/JsonTest.json', function (json) {
alert("GET JSON !");
});
Is it somehow not finding the directory structure ?
thanks.
Bob
The first one definitely won't work, since ~ doesn't mean anything client-side. What actual URL is requested by the second example? Does it send an AJAX request at all? What is the response?
If you have a dynamic server-side URL then you'll want to use server-side code to dynamically build it in the rendered output. Something like this:
$.ajax({
url: '#Url.Content("~/xml/JsonTest.json")',
type: 'GET',
dataType: 'json',
success: function (json) {
alert("HI");
}
});
This would result in the client-side JavaScript being rendered with the full URL for the server-side path "~/xml/JsonTest.json".
Best solution for my case was to properly code it up in a C# method as follows :
public string getJsonParameters()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
string jsonStr = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/myKeys.json"));
JsonParameters jsonData = (JsonParameters)ser.Deserialize(jsonStr, typeof(JsonParameters));
return jsonStr;
}
in my previos question Asp MVC 3 json complex object not initialize properties
My mistake was in JSON convert from Knockout and after one more time with JSON.stringify(data).
Now evering working fine with one parameter,
but I wonder about if I need send to MVC controller two or more parameters one of them is knowckout data = ko.toJSON(viewModel); variable other one is some text.
var settings = ko.toJSON(viewModel);
var parameters = JSON.stringify({ id : *"guid"*, data : settings });
$.ajax({
url: '/KioskAjax/SaveSettings/',
type: "POST",
data: parameters,
dataType: "JSON",
contentType: "application/json; charset=UTF-8",
success: function (result) {
alert('ok');
}
});
[HttpPost]
public JsonResult SaveKiosksSettings(Guid id, GlobalData data)
{
return Json(false.ToString(), JsonRequestBehavior.AllowGet);
}
In this example id is getting value, but GlobalData parameters is null again,
i think this is because I use JSON.stringify again, but how build correct JSON for controller call if I have knowckout object ?
thanks.
ko.toJSON(myObject) does a ko.toJS(myObject) and then a JSON.stringify(myObject).
So, you could choose to use ko.toJS(myObject) to get a clean copy of your data and then JSON.stringify it with your other data, as you are already doing.
I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:
$('#Search').click(function () {
var query = $('#query').valueOf();
$.ajax({
url: '/Products/Search',
type: "POST",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
for (var x = 0; x < data.length; x++) {
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
$(content).appendTo("#ProductList");
// updateListing(data[x]);
}
}
});
});
It seems that the JSON object is being returned correctly because "alert(data)" displays the following
[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]
but when I try displaying the Id or Name to the page using:
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
it returns "undefined" to the page. What am I doing wrong?
Thanks for the help.
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
It works fine,
Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do
alert(data)
if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert
[object Object]
If this the response then you can be sure that you can use this as an object (json in this case).
Thus, you need to convert your string into json first, before using it by doing this:
JSON.parse(data)
Well... you are about 3/4 of the way there... you already have your JSON as text.
The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.
It isn't... its just a string.
Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.
You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.
myResult = JSON.parse(request.responseText);
Now myResult is a javascript object containing the properties that were transmitted through AJAX.
That should allow you to handle it the way you appear to be trying to.
Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.
For the record, this was already answered by Andy E for someone else HERE.
edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.
Try the jquery each function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this
$.ajax({
url : url,
dataType : 'json'
})
.done(function(data, statusText, resObject) {
var jsonData = resObject.responseJSON
})
From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType to json to convert it automatically.
parse and convert it to js object that's it.
success: function(response) {
var content = "";
var jsondata = JSON.parse(response);
for (var x = 0; x < jsonData.length; x++) {
content += jsondata[x].Id;
content += "<br>";
content += jsondata[x].Name;
content += "<br>";
}
$("#ProductList").append(content);
}
Use
dataType: 'json'
In .NET you could also return Json(yourModel) in your action method/API controller.
And parse the returned JSON as follows in the Jquery .ajax:
if you've a complex object: navigate to it directly.
success: function (res) {
$.each(res.YourObject, function (index, element) {
console.log(element.text);
console.log(element.value);
});
});