Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

ajax - Can you add headers to getJSON in jQuery?

ive been looking to get JSON data for pinterest but notice they currently dont let you get for a user and a specific board so found mashape and i need to get the API key but using header request can this be done using getJSON? current code is:

I need to pass: "X-Mashape-Key: KEY_HERE" i see it can be done in ajax but dont know how to rewrite the getJSON as the loop to that but can see here:

http://blog.mashape.com/mashape-sample-code-executing-ajax-request-using-jquery/

$.getJSON(settings.apiPath + settings.username + '/boards/', function (data) {
            beforeSend: setHeader,
            console.log(data);

            for (var i = 0; i < settings.count; i++) {
                var feed = false;
                if(data.data[i]) {
                    feed = data.data[i];
                }

                var temp_data = {
                    message: truncate(feed["message"], 100),
                    url: feed["link"]
                };

                $('#pinterestFeed ul').append('<li class="feed">' + templating(temp_data) + '</li>');
            }
            $(".pinterest #loading").hide();  
        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$.getJSON is a shorthand for

$.ajax({
    dataType: "json",
    url: url,
    data: data,
    success: success
});

So you can simply use it directly like

$.ajax({
    beforeSend: function(request) {
        request.setRequestHeader("X-Mashape-Key", 'key_here');
    },
    dataType: "json",
    url: settings.apiPath + settings.username + '/boards/',
    success: function(data) {
        //Your code
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...