简体   繁体   中英

Reading javascript from xml

I have a list of strings I want to put in a XML file and include the file into the web pages. So when I do validation on client side using javascript. I can read those strings from the XML and parse it immediately. Something like this

blabla.cshtml
<includebla> path to xml </includebla>
<script type="javascript">
read xml
parse string
</script>

The point is: I want to keep my strings in a file so the browser won't download the data again and again, but I don't know if I can reference a XML file in .cshtml and read it in javascript. Can anybody give a hint? I really appreciate it. Thanks

If its just a list of strings, consider putting them in a JS object and include a link to JS file in your cshtml.

resources.js

var resources = {
      "id1": "sample string 1",
      "id2": "sample string 2",
      "id3": "sample string 3",
}

In your JS file, you can then say:

site.js

function getStringById(id) {
    return resources[id];
}

You escape the rigor of XML parsing and JS files can be cached easily by browser.

alert(getStringById("id1"));

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