Recently, I have been working on e-commerce projects, including buyers and sellers in seller.com, buyer.com, and www.xxx.com.
One of the drop-down boxes for viewing the second-level product categories needs to be queried. If these three items are not considered at the time, they will be used in the front-end code, and the background requirements will change, this interface is also used by sellers and buyers in the background.
Since the front-end page is initialized Using ajax to initialize this drop-down box, the call of other platforms also comes to mind this problem, and then the problem of Ajax cross-origin occurs, the solution is provided below.
The following code of action is called by three systems.
Public class headaction extends baseaction {private httpservletrequest request; private httpservletresponse response; Public void findsecondcat () {actioncontext CTX = actioncontext. getcontext (); Request = (httpservletrequest) CTX. get (servletactioncontext. http_request); response = (httpservletresponse) CTX. get (servletactioncontext. http_response); // response. setheader ("cache-control", "No-Cache"); respons E. setcontenttype ("text/JSON; charset = UTF-8"); string cattype = request. getparameter ("cattype"); List <categorynode> node = categorycache. getallcategorynodes (1, integer. parseint (cattype); // call the cache query category try {printwriter out = response. getwriter (); jsonarray ja = new jsonarray (); For (categorynode C: node) {// return the JSON format jsonobject J = new jsonobject (); J. put ("ID", C. ID); J. put ("name", C. name); Ja. add (j);} string cb = Request. getparameter ("Callback"); // If Ajax requests contain this parameter, you can trace the firbug of firfox to see if (CB! = NULL) {// if it is a cross-domain stringbuffer sb = new stringbuffer (CB); sb. append ("("); sb. append (Ja. tostring (); sb. append (")"); out. write (sb. tostring (); out. close ();} else {// out of non-Cross-Domain conditions. write (Ja. tostring (); out. close () ;}} catch (ioexception e) {e. printstacktrace ();}}}
Below is the JS Code
$. Ajax ({type: 'get', URL: '<% = com. utils. pubconstant. wwwdomain %>/index/findsecondcat. action ', data: {cattype: 1}, datatype: 'jsonp', // jsonperror: function () {}, success: function (data) must be used for cross-Origin) {inneroption = "<option value =''> all categories </option> "; for (VAR I = 0; I <data. length; I ++) {inneroption + = '<option value = "' + data [I]. ID + '">' + data [I]. name + '</option>'; your desired parameter ('{secondcatidid'{.html (inneroption); $ ("# Lang, # secondcatidid "). jlistbox ();}});
In this way, Ajax requests can be made across domains.