简体   繁体   中英

Can I store XML from a Google API in Javascript as a string?

Before I begin my question: Last time I asked this question a couple of you posted helpful links to parsing the XML. But my question is asking how to get the XML information into a string variable in the first place. It is NOT a duplicate of those links.

Hopefully my question makes sense. But I am trying to store the XML I get from the Google geocode API ( https://developers.google.com/maps/documentation/geocoding/intro ) so I can autoformat addresses that people type into some fields.

Essentially I am looking for a Javascript equivalent of =WEBSERVICE([URL]) in MS Excel.

The idea is to retrieve the address fields that people type, put it into the geocode URL, store the XML as a string (this is the step I am having trouble with), and then set the fields to the results gotten from the API.

A simple example using jQuery:

var response = $.get('https://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY');
var text = response.responseText;

$.get will return a jqXHR object, which exposes responseText . You can check out https://api.jquery.com/jquery.ajax/ for more details.

Note: The above example WILL return an error (since we are not providing an API key), but the response format is the same.

To actually convert an XMLDocument to a string, you would have to use a serializer (see Convert xml to string with jQuery ).

The other guy's answer didn't work for me for some reason. But using the code structure here did: How do I get the entire XML string from a XMLDocument returned by jQuery (cross browser)?

I simply replaced the url with the Google API's (and replaced the dataType to XML as the answer suggested).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM