Get json data via ajax

Hope this is a pretty simple question. Forgive my ignorance, but I'm mostly a PHP / Zend developer, so I'm struggling a bit with C # and Visual Studio with the json / ajax problem. Is there something obvious that I'm missing? Any help would be appreciated. Should I look at List<> ?

Here is the error I get when I run the javascript ajax function: Msgstr "Unknown getwidgets web method."

I have a C # dataset that I run through a JSON converter. This works well and returns my data in a JSON string.

 private widgetsBL widgetsBLObject = new widgetsBL(); [WebMethod] public String getwidgets() { DataSet results = new DataSet(); results = widgetsBLObject.selectTheWidgets(); string jsresults = MyClassLibrary.JqueryTools.GetJSONString(results.Tables[0]); return jsresults; } 

Here is jsresults:

 {"Table" : [ {"widgetid" : "1","widgetname" : "gizmo1000","widgetdescription" : "very cool widget"}, {"widgetid" : "2","widgetname" : "gizmo2000","widgetdescription" : "decent widget"}, {"widgetid" : "3","widgetname" : "gizmo3000","widgetdescription" : "terrible widget"} ]} 

My Javascript call:

 $.ajax({ type: "POST", url: "my.aspx/getwidgets", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { // do stuff with returned data } }); 
+4
source share
3 answers

getwidgets must be static

 [WebMethod] public static String getwidgets() 
+1
source

Remember that if you want your method to be invoked with JavaScript, you need to tag your ScriptMethodAttribute method. So it looks like this:

 [ScriptMethod] [WebMethod] public static String getwidgets() { // Your core here } 

I would return the method, the object itself, and not the serialized version, because ASP.NET will JSON serialize it for you if you mark it as [ScriptMethod]; therefore, in the client, your data.d variable will contain the object itself, and not a simple string, which you will have to deserialize later, as in your current implementation.

+1
source

You mix technologies: my.aspx is designed to display HTML content, but it can be used to implement REST functionality.

In your case, it is easiest to implement your code as part of the Page_Loaded () method. Make sure you clear the answer first (so you don't have extra markup in the answer). Alternatively, you can set the content type of your response to JSON (and not the default html):

  protected void Page_Load(object sender, EventArgs e) { Response.ClearContent(); Response.ContentType = "application/json"; DataSet results = new DataSet(); results = widgetsBLObject.selectTheWidgets(); string jsresults = MyClassLibrary.JqueryTools.GetJSONString(results.Tables[0]); return jsresults; } 

Then you will get a JSON string in my.aspx (without getwidgets).

Also, since you are not posting any data, consider using GET rather than POST in an AJAX call.

0
source

Source: https://habr.com/ru/post/1403504/


All Articles