How do I send a cross-domain POST request via JavaScript?

后端 未结 17 2397
说谎
说谎 2020-11-21 05:06

How do I send a cross-domain POST request via JavaScript?

Notes - it shouldn\'t refresh the page, and I need to grab and parse the response afterwards.

17条回答
  •  梦如初夏
    2020-11-21 05:50

    If you want to do this in ASP.net MVC environment with JQuery AJAX, follow these steps: (this is a summary of the solution offered at this thread)

    Assume that "caller.com"(can be any website) needs to post to "server.com"(an ASP.net MVC application)

    1. On the "server.com" app's Web.config add the following section:

        
            
                
                
                
            
        
      
    2. On the "server.com", we'll have the following action on the controller(called "Home") to which we will be posting:

      [HttpPost]
      public JsonResult Save()
      {
          //Handle the post data...
      
          return Json(
              new
              {
                  IsSuccess = true
              });
      }
      
    3. Then from the "caller.com", post data from a form(with the html id "formId") to "server.com" as follow:

      $.ajax({
              type: "POST",
              url: "http://www.server.com/home/save",
              dataType: 'json',
              crossDomain: true,
              data: $(formId).serialize(),
              success: function (jsonResult) {
                 //do what ever with the reply
              },
              error: function (jqXHR, textStatus) {
                  //handle error
              }
          });
      

提交回复
热议问题