使用jQuery.ajax请求和jsonp进行基本身份验证 [英] Basic Authentication with jQuery.ajax request and jsonp

查看:190
本文介绍了使用jQuery.ajax请求和jsonp进行基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些本地的html / js文件,我想通过https调用一些远程服务器,并最终使用基本身份验证来处理请求。

I have some local html/js files with which I'd like to invoke some remote servers via https and eventually use Basic Authentication for the request.

我是遇到两个问题。首先,如果我没有为dataType指定'jsonp',jQuery.ajax()请求将返回错误:

I am encountering two problems. First is that if I don't specify 'jsonp' for the dataType, jQuery.ajax() request returns the error:


访问受限制的URI拒绝代码:
1012

Access to restricted URI denied code: 1012

我的请求是否被视为跨域,因为我的主要工作文件存储在本地,但从其他地方的服务器检索数据?

Are my requests considered cross-domain because my main work file is stored locally, but retrieving data from a server elsewhere?

很好,我更新了电话,现在它看起来像:

So fine, I update the call so it now looks like:

$.ajax({ 
     url: myServerUrl,
     type: "GET", 
     dataType: "jsonp", // considered a cross domain Ajax request if not specified
     username: myUsername,
     password: myPassword,

     success: function(result)
     {
        // success handling
     },
     error: function(req, status, errThrown){
         // error handling
     }
})

因为我需要使用基本身份验证,所以我传递了用户名/密码但是如果我监视请求,我看不到它被设置,此外,服务器发送错误响应,因为它没有预期的信息。

Because I need to use Basic Authentication, I'm passing in the username/password but if I monitor the request, I don't see it being set and additionally, the server sends an error response since it doesn't have the expected info.

另外,因为我有 jsonp 设置, beforeSend 将不会被调用。

Additionally, because I have jsonp set, beforeSend won't get invoked.

如何使用基本身份验证为此请求传递凭据?

How do I pass along the credentials using Basic Authentication for this request?

推荐答案

短版本是你不能这样做的。您的怀疑是正确的,因为您是本地的,这些文件是远程的,您无法访问它们,您被同源政策。解决方法是 JSONP ,但这似乎并不适用于你的情况......

The short version is you can't do this. Your suspicions are correct, because you're local and these files are remote, you can't access them, you're being blocked by the same-origin policy. The work-around for that is JSONP, but that really doesn't seem to apply to your situation...

JSONP的工作方式不同,它是通过< script> 标签包含的GET请求获取文件,因此您不会发送特殊标题或任何内容。

JSONP works differently, it's a GET request via a <script> tag include to get the file, so you're not sending special headers or anything.

您需要通过您所在的服务器代理请求(域名所在此脚本正在运行)或其他代理选项,但是从客户端到另一个域的访问被阻止,主要是出于安全原因。

You'll need to proxy the request through the server you're on (the domain of where this script is running) or another proxy option, but going from the client to another domain is blocked, mainly for security reasons.

这篇关于使用jQuery.ajax请求和jsonp进行基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆