1

我有点想不通,情况如下:

我在不在同一台机器上的 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());                    
        }
        });

参数很好,经过测试,web方法也正确。

作为错误消息,我得到了这个:

  • Firefox:[异常...“失败”nsresult:“0x80004005(NS_ERROR_FAILURE)”位置:“JS 框架 :: http:// localhost:7515/jquery-1.8.3.js :: :: line 8434”数据:否]
  • Chrome:错误:NETWORK_ERR:XMLHttpRequest 异常 101
  • IE8:无传输

如果我在同一台机器上运行的 Web 服务上使用相同的代码段,则没有问题。如果我通过 Web 界面使用远程 Web 服务,它也可以正常工作。

PS:我google了一下,有些页面推荐了一些跨域参数,这也不起作用。不幸的是,我猜使用相对路径是行不通的。

感谢您提前做出的任何努力。

溴 vm370

更新:好吧,我更新了我的代码以根据我现有的请求执行 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;

}

从FF我得到错误500,在IE8中请求落在xhr.onerror子句中......有什么想法吗?

4

2 回答 2

4

同源政策在这里发挥作用。您无法与另一个域进行通信。这是为了保护您的隐私,因此某些网页无法与您的电子邮件、银行帐户等进行通信。

如果其他域支持CORS,只要浏览器支持,您就可以发出该类型的请求。如果不支持 CORS,则必须使用本地代理或 JSONP 请求 [服务器也必须支持 JSONP。]

于 2012-12-11T17:26:07.827 回答
0

我做了一点头发拉过这个,这对我有用。

// 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);    
        }
  });
}

注意额外的'?callback=?' get 方法调用的 url 中的查询字符串参数。

现在在服务器端脚本上有一些权限设置可以用于远程 ajax 调用。我不确定这些设置有多安全。

get 方法调用的响应准备略有不同。它需要将您的 json 响应包装在传递给服务器的回调函数名称中。Jquery 会自动在查询字符串'?callback=somethingfromjquery'中放置一个值。所以我们使用 $_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).')';
}    

?>

如果您需要从表单上传文件,则无法使用 ajax get 方法调用来完成,因为表单序列化不包含文件。您可以使用 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);  
        }             
     });    
  }
于 2014-02-22T13:37:00.823 回答