如何将param发送到远程文件

时间:2012-08-03 14:14:25

标签: php jquery ajax

我的脚本像这样

$(function(){
    //attach autocomplete  
    $("#user_key").autocomplete({
            //define callback to format results  
                source: function(req, add){
                    //pass request to server  
                    $.getJSON("/ajax/user_autocomplete.php?user_key=?",req, function(data){
                        //create array for response objects
                        var suggestions = [];
                        //process response
                        $.each(data, function(i, val){
                        suggestions.push(val.name);  
                    });
                    //pass array to callback
                add(suggestions);
            });
        }
    });
});

并希望将一个参数发送到php文件以接收答案,我该如何在此脚本中执行此操作?并且有必要在html中使用 method =“get”或者这不重要吗?

我要写 {param:$(this).val}而不是req 或者怎么做?

2 个答案:

答案 0 :(得分:0)

req参数将是包含属性term的对象。需要为$.getJSON的第二个参数定义此参数和任何其他GET参数

function(req, add){
                var params = {
                    user_key: myUserKeyVar,
                    term : req.term,
                    otherKey: myOtherKey
                };
                //pass request to server  
                $.getJSON("/ajax/user_autocomplete.php",params, function(data){
                    //create array for response objects
                    var suggestions = [];
                    //process response
                    $.each(data, function(i, val){
                    suggestions.push(val.name);  
                });
                //pass array to callback
            add(suggestions);

答案 1 :(得分:0)

只是做:

       $('#user_key').autocomplete(
        {
            source: '/ajax/user_autocomplete.php'
        });

只要您从user_autocomplete.php发回正确的JSON,那么一切都很好。