开发者

Populating a drop down list using jQuery getJSON not working

开发者 https://www.devze.com 2023-01-15 20:40 出处:网络
I am trying to send a variable with jQuery\'s getJSON function but it doesn\'t seem to be going through, I am also unsure of how to get the variable I have just sent in the waiting PHP file, do I just

I am trying to send a variable with jQuery's getJSON function but it doesn't seem to be going through, I am also unsure of how to get the variable I have just sent in the waiting PHP file, do I just reference it via the name I sent it as, for instance if I send a variable called 'test', can I get it like this, $_POST['test'] on the other side开发者_运维技巧? or how exactly would that work?

I am trying to populate a drop down list using the method below, any advice on improving the code would be greatly appreciated!

Here is what the PHP returns:

[{"city":"One"},{"city":"Two"},{"city":"Three"},{"city":"Four"}]

jQuery:

//get the cities
$("#province").live('change', function(){
    var test = $('#province').val();
    //alert(test);

    $.getJSON("cities.php", test, function(data){

    //clean out the select list
    $('#city').html('');

        //run the loop to populate the drop down list
        $.each(data, function(i, data) {
            var city = data.city;     

            $('#city').append(
                $('<option></option>').html(city)
            );
        });
    });
});

PHP:

$province = $_POST['test'];

//mySQL query here

$myarray = mysql_fetch_array($query, true);
$string = explode(',', $myarray['cities']);

foreach($string as $key=>$value) {
    $string[$key] = array('city'=>$value);
}

$json = json_encode($string);
echo $json;

What could I be doing wrong?

Thanx in advance!


A couple of things, first, getJSON is a get ajax call. So, you should be expecting the data you pass using getJSON to end up in $_GET and obviously $_REQUEST, but not $_POST. Secondly, you have to pass an object which describes a map of data which will be reflected in the associative array, $_GET.

So your code should read...

$.getJSON("cities.php", { test: $('#province').val() }, function (data) {

with that, you can access on PHP side as $_GET['test']

A few improvements I can give... (untested)

//get the cities
$("#province").live('change', function(){

    $.getJSON("cities.php", { test: $('#province').val() }, function(data){

        if(!data.ok) {
            alert('Error getting cities. Please try again later.');
        }

        var markup = '', len = data.cities.length;

        for(var i = 0; i < len; i++) {
            markup += '<option>' + data.cities[i] + '</option>';
        }

        $('#city').html(markup);

    });

});

and php

$province = $_POST['test'];

//mySQL query here

$myarray = mysql_fetch_array($query, true);
$cities = explode(',', $myarray['cities']);

echo json_encode(array(
    'ok' => true,
    'cities' => cities
));

Good luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消