I have a few select menus that I would like to populate using json from my php script (each select menu shows different values depending on the contents of the other select menus). I know how to clear and fill a select menu from the js as long as I have an array to work with. The problem is that I don't know how to use the ajax call to retrieve an array or json for the javascript to populate the select menu with.
I do not wish to use jquery as it is simply too big for such a simple task imho.
I would appreciate any comments regarding this matter.
My test script for populating a menu:
var sl = document.getElementById(foo);
sl.options.length = 0;
for(var i=0;i<100;i++){
sl.options[i] = new Option(i + "Option text", i+"optionValue");
}
Thank you.
Zepto是jQuery的轻量级实现,它具有JQ ajax支持,它非常小,可以为您节省大量时间。
If you have control over the PHP script, then the easiest (native) way is to use JSON-P.
On the server:
<?php
$callback = $_GET['callback'];
$json = json_encode($data);
print $callback . '(' . $json . ');';
?>
and on the client:
<script>
function getJSON() {
var script = document.createElement('script');
script.src = 'http://mysite.com/page.php?callback=updateSelect';
document.getElementsByTagName('head')[0].appendChild(script);
}
function updateSelect(json) {
// do stuff with your JSON object
}
getJSON();
</script>
This makes a basic GET request to your remote page; the page prints the encoded JSON wrapped in a callback name you provided, which in this case immediately calls the updateSelect
method, passing in the JSON object.
If I understand your question correctly, you are looking for sending a request to the server, and getting back some data in a json format, without using jQuery (and potentially - without using any other library).
Well, very easy ... welcome to year 2000, before 'prototype', 'jQuery' and the other libraries were invented, and before the term 'Ajax' was coined (although the paradigm was already in use).
<script type="text/javascript"
src="http://blogname.blogspot.com/feeds/posts/default?alt=json-in-script&callback=myFunc"
></script>
Take a look at this URL (it returns recent posts from Google's blogpost). Note that everything is embedded within a call to the function myFunc, passed as an argument.
You can embed the <script>
element in your code, or you can generate it on the fly with document.write
, or you can even use the DOM manipulation to add element to the element of type SCRIPT.
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.