【问题标题】:Convert Jquery Ajax to Pure JavaScript Ajax [duplicate]将 Jquery Ajax 转换为纯 JavaScript Ajax [重复]
【发布时间】:2016-07-18 02:32:32
【问题描述】:

我想将 Jquery Ajax 转换为 Pure JavaScript Ajax,希望有人可以帮助我,

jQuery

$.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: accessURL,
            dataType: 'jsonp',
            success: function (data) {        
                var dataLen = data.results.length;
                // console.log("api returned " + dataLen + " total results");

                 $.each(data.results, function (i, val) {
                     var venueObj = val.venue;
                     //console.log(venueObj);

                    if ( ( venueObj && venueObj.lat != 0) ) {

                        meetupName.push(val.name);
                        meetupDescript.push(val.description);
                        meetupUrl.push(val.event_url);

                        //meetupLat = [];
                        meetupLat.push(venueObj['lat']);
                        //meetupLong = [];
                        meetupLon.push(venueObj['lon']);

                        //address
                        meetupAddress.push(
                            venueObj['address_1'] + "</h3><h3>" +
                            venueObj['city']
                        );

                    } else {
                        return;
                    }

                });

                //console.log(data.results);

                //console.log(meetupLon);
                meetupLon = _.without(meetupLon, 0);
                //console.log(meetupLon);
                meetupLat = _.without(meetupLat, 0);
                //console.log(meetupLat);

                //console.log(meetupAddress);


                for (i=0; i < meetupLat.length; i++) {
                    //set the markers.    
                    myLatlng = new google.maps.LatLng(meetupLat[i], meetupLon[i]);

                    allMarkers = new google.maps.Marker({
                        position: myLatlng,
                        map: map,
                        title: "Meetup",
                        html:
                                '<div class="markerPop">' +
                                    "<h2>"+ meetupName[i] +"</h2>" +
                                    "<h3>"+ meetupAddress[i] +"</h3>" +
                                    "<p>"+ meetupDescript[i] +"</p>" +
                                    "<a href='"+ meetupUrl[i] +"'>"+ meetupUrl[i] +"</p>" +

                                '</div>'
                    });

                    allLatlng.push(myLatlng); 
                    //console.log(allLatlng);

                    google.maps.event.addListener(allMarkers, 'click', function () {
                        infowindow.setContent(this.html);
                        infowindow.open(map, this);
                    });

                    //  Make an array of the LatLng's of the markers you want to show
                    //  Create a new viewpoint bound
                    var bounds = new google.maps.LatLngBounds ();
                    //  Go through each...
                    for (var i = 0, LtLgLen = allLatlng.length; i < LtLgLen; i++) {
                      //  And increase the bounds to take this point
                      bounds.extend (allLatlng[i]);
                    }
                    //  Fit these bounds to the map
                    map.fitBounds (bounds); //Finished !(a)


                } //end for loop


            }
        }); //end ajax request

我在这里看到了一些代码。 http://youmightnotneedjquery.com/这是代码

纯 Javascript

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var resp = request.responseText;
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

如何设置contentTypedataType

【问题讨论】:

  • @Paul Draper 你能帮我吗,

标签: javascript jquery ajax google-maps meetup


【解决方案1】:

试试:

function jsonp(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    window[callbackName] = function(data) {
        delete window[callbackName];
        document.body.removeChild(script);
        callback(data);
    };

    var script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    document.body.appendChild(script);
}

jsonp('https://api.meetup.com/2/open_events.json?zip=12233&page=30&category=34&time=,1w&key=1719487a4a3c39b3e241e181837529', function(data) {
   alert(data.meta.description);
});

https://jsfiddle.net/tgL5v0yo/

注意:

JSONP 不使用 XMLHttpRequests。 使用 JSONP 的原因是为了克服 XHR 的跨域限制。

【讨论】:

  • 数据类型如何?抱歉我不擅长纯javascript
  • Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 我仍然无法收到请求。
  • 请把它包含在我的script idk 中,我很困惑,对不起
  • 我认为这是可行的,但我收到错误 {"details":"API requests must be key-signed, oauth-signed, or accompanied by a key: http:\/\/www.meetup.com\/meetup_api\/docs\/#authentication","code":"not_authorized","problem":"You are not authorized to make that request"}
  • 好像是变量的问题,现在试试
【解决方案2】:

问题就在这里:

request.onload

尝试替换为

request.onreadystatechange

要继续使用request.onload,请参阅此onreadystatechange

更多信息Using XMLHttpRequest

更新 1

var request = new XMLHttpRequest();
request.withCredentials = true;
request.open('GET', '/my/url', true);

【讨论】:

  • 我收到错误Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
  • 那是一个 php,所以我想我不能使用它。
  • 您尝试使用这种纯 JavaScript 方法访问的网址是什么?
  • https://api.meetup.com/2/open_events.json?zip=12233&amp;page=30&amp;category=34&amp;time=,1w&amp;key=1719487a4a3c39b3e241e181837529
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
相关资源
最近更新 更多