简体   繁体   English

JQuery Ajax对远程Web服务的POST请求

[英]JQuery Ajax POST request to remote web service

I somehow can't figure it out, the situation is as follows: 我莫名其妙地想不出来,情况如下:

I'm calling a method on a web service that is not on the same machine and use the following JS snippet in my script: 我正在调用不在同一台机器上的Web服务上的方法,并在我的脚本中使用以下JS代码段:

$.ajax({
            type: "POST",
            url: "http://" + gServer + "/xawebservice/xawebservice.asmx/" + webMethod,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            async: false,
            data: WSParameters,
            success: function callFunction(result) { processResults(result, pType, pParam1); },
            error: function (xhr, status, error) {
                alert(error.toString());
                //alert(xhr.toString());                    
        }
        });

Parameters are fine and tested, the web method is also correct. 参数很好并且经过测试,web方法也是正确的。

As an error message I get this: 作为错误消息,我得到这个:

  • Firefox: [Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http:// localhost :7515/jquery-1.8.3.js :: :: line 8434" data: no] Firefox:[例外......“失败”nsresult:“0x80004005(NS_ERROR_FAILURE)”位置:“JS frame :: http:// localhost :7515 / jquery-1.8.3.js :: :: line 8434”数据:否]
  • Chrome: Error: NETWORK_ERR: XMLHttpRequest Exception 101 Chrome:错误:NETWORK_ERR:XMLHttpRequest异常101
  • IE8: No Transport IE8:没有运输

If I'm using the same snippet on a web service that is running on the same machine, there is no problem. 如果我在同一台计算机上运行的Web服务上使用相同的代码段,则没有问题。 And if I use the remote web service over the web interface, it's also working fine. 如果我通过Web界面使用远程Web服务,它也可以正常工作。

PS: I googled around a bit and some pages were recommending some cross domain parameters, which didn't work either. PS:我搜索了一下,有些页面推荐了一些跨域参数,这些参数也无效。 Unfortunately using a relative path will not work I guess. 不幸的是,我想使用相对路径是行不通的。

Thanks for any efforts in advance. 感谢您提前做出的任何努力。

Br vm370 Br vm370

UPDATE: Alright I updated my code to execute a CORS request based on my existing one, but I get an error 500, executing the request on the server directly is working fine and CORS is activated on the server. 更新:好吧我更新了我的代码,根据我现有的代码执行CORS请求,但是我得到一个错误500,直接在服务器上执行请求工作正常,并在服务器上激活CORS。

function xenappRequest(pType, pParam1) {

// CORS request    
var url = "http://" + gServer + "/webservice/webservice.asmx/webMethod";
var params = { "appName": pParam1 };
var xhr = createCORSRequest("POST", url);
if (!xhr) {
    alert('CORS not supported');
} else {
    // Do the request
    // Response handlers.
    xhr.onload = function () {
        //var text = xhr.responseText;
        alert('Response from CORS request to ' + url + ': ' + xhr.response);
    };
    xhr.onerror = function () {
        alert('Woops, there was an error making the request.');
    };
    xhr.send(JSON.stringify(params));
}

} }

function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
    // Check if the XMLHttpRequest object has a "withCredentials" property.
    // "withCredentials" only exists on XMLHTTPRequest2 objects.
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
    // Otherwise, check if XDomainRequest.
    // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    // Otherwise, CORS is not supported by the browser.
    xhr = null;
}
return xhr;

} }

From FF i get the error 500, in IE8 the request lands in the xhr.onerror clause... Any ideas? 从FF我得到错误500,在IE8中请求登陆xhr.onerror子句...任何想法?

Same Origin Policy is in play here. 同源政策在这里发挥作用。 You can not communicate with another domain. 您无法与其他域通信。 It is to protect your privacy so some web page can not communicate with your email, bank accounts, etc. 这是为了保护您的隐私,因此某些网页无法与您的电子邮件,银行帐户等进行通信。

If the other domain supports CORS , you can make that type of request as long as the browser supports it. 如果其他域支持CORS ,只要浏览器支持该请求,您就可以进行该类型的请求。 If there is no support for CORS, you would have to use a local proxy or a JSONP request [server has to support JSONP also.] 如果不支持CORS,则必须使用本地代理或JSONP请求[服务器也必须支持JSONP。]

I did my bit of hair pulling over this and here is something that works for me.. 我做了一点头发拉这个,这里的东西对我有用..

// js/jquery /////////

// post method call 
function  myajaxcall_post(){     
    $.ajax({ 
            url: 'http://' + url_path_on_remote_server,
            cache: false,
            type : "POST",            
            data: {request_param1: 'something1', request_param2: 'something2' },
            dataType: 'json',
            success: function(response)
            {
                console.log(response); 
            }            
      });
}

// get method call
function  myajaxcall_get(){     
$.ajax({ 
        url: 'http://' + url_path_on_remote_server + '?callback=?',
        cache: false,            
        type : "GET",            
        data: {request_param1: 'something1', request_param2: 'something2'},
        dataType: 'json',
        success: function(response)
        {
            console.log(response);    
        }
  });
}

Note the additional '?callback=?' 注意额外的'?callback =?' query string argument in the url for the get method call. 在get方法调用的url中查询字符串参数。

Now on the server side script there are some permission settings to do for remote ajax calls. 现在在服务器端脚本上有一些权限设置可用于远程ajax调用。 I am not sure how secure these settings are. 我不确定这些设置有多安全。

The response for get method calls are prepared a little differently. get方法调用的响应准备有点不同。 It needs your json response wrapped in the callback function name that is passed to the server. 它需要包含在传递给服务器的回调函数名称中的json响应。 Jquery automatically puts a value there in the query string '?callback=somethingfromjquery' . Jquery自动在查询字符串'?callback = somethingfromjquery'中放置一个值。 So we use $_GET['callback'] to get the name of that callback function. 所以我们使用$ _GET ['callback']来获取该回调函数的名称。

<?php  
// server side php script ////////////////

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])){
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    }         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])){
        header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    }
}

// Send some response //////////////
//print_r($_POST);
//print_r($_GET);

$response = array();
$response['message'] = 'Response from '.$_SERVER['HTTP_HOST'];

if(isset($_POST)){ 
    echo json_encode($response);
}
elseif(isset($_GET)){
   echo $_GET['callback'].'('.json_encode($response).')';
}    

?>

If you need to upload files from forms you cannot do it with ajax get method calls because form serialize doesn't include files. 如果您需要从表单上传文件,则无法使用ajax get方法调用,因为表单序列化不包含文件。 You could use a ajax post method call with what the FormData() provides. 您可以使用FormData()提供的ajax post方法调用。

// js/jquery - for forms with file uploading 

function myajaxcall_submitform(){

     // put your form id 
    fdata = new FormData( document.getElementById('form1') ); 

    // add additional fields to form if any to post with
    fdata.append('upload_file_flag', 1);    

    $.ajax({ 
        url: 'http://' + url_path_on_remote_server,
        cache: false,
        type: "POST",            
        data: fdata,
        processData: false, // need this for FormData 
        contentType: false, // need this for FormData 
        dataType: 'json',
        success: function(response)
        {
                console.log(response);  
        }             
     });    
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM