jQuery Ajax Unauthorized 401 Error

回眸只為那壹抹淺笑 提交于 2019-12-25 14:11:51

问题


I have this code:

<?php
$username = $_POST['username'];
$password = $_POST['password'];
$ck = time();
$read = new GoogleReaderAPI( $username, $password );
$token = $read->getToken();

echo "RSS Feed: <input type='text' name='rss_feed' /> <br /> ";
echo "<input type='hidden' value='$token' id='token' />";
echo "<input type='hidden' value='$ck' id='ck' />";
echo "<input type='hidden' value='$username' id='username' />";
echo "<input type='hidden' value='$password' id='password' />";
echo '<input type="button" value="Submit" id="click"/>';
echo "<div id='result'></div>";
?>
<script>
jQuery("#click").click(function(){
    var quickadd = escape( jQuery("input[name=rss_feed]").val() );
    var T = escape( jQuery("#token").val() );
    var ck = escape( jQuery("#ck").val() );
    var params = "quickadd="+quickadd+"&T="+T;

        jQuery.ajax({
            type: "POST",
            url: "http://www.google.com/reader/api/0/subscription/quickadd?ck="+ck+"&client=scroll",
            data: params,
            contentType: "application/json",
            success: function(data){
                alert(data);
            }
        });
    });

I'm getting a 401 Unauthorized error when using ajax but when I try to use an ordinary POST method (non-ajax), then I am able to see the output.
This is an exmaple ouput that i'm seeing when using an ordinary POST

{"query":"http://feeds.feedburner.com/TechCrunchIT","numResults":1,"streamId":"feed/http://feeds.feedburner.com/TechCrunchIT"}

By the way i'm integrating the google reader account in my application that is why i'm calling that one in the ajax-url.


回答1:


This should help you

jQuery.ajax({
            type: "POST",
            url: "http://www.google.com/reader/api/0/subscription/quickadd?ck="+ck+"&client=scroll",
            data: params,
            contentType: "application/json",
            beforeSend: function(xhr) {
                 xhr.setRequestHeader("Authentication", "Basic " + encodeBase64(username + ":" + password) //May need to use "Authorization" instead
            },
            success: function(data){
                alert(data);
            }
        });


来源:https://stackoverflow.com/questions/8847748/jquery-ajax-unauthorized-401-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!