douou6807
douou6807
2013-12-09 15:00

使用jQuery和$ .ajax将变量传递给PHP

已采纳

I have a jQuery php script which accesses a database and echoes back html to fill a div on my page. It uses the following code.

function myCall() {
    var request = $.ajax({
        url: "ajax.php",
        type: "GET",
        dataType: "html"
    });

    request.done(function (msg) {
        $("#divholder").html(msg);
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
}

What I need to do is also send a variable through to the script so it knows what to look for in the database. I have been searching but I can't seem to find quite the right answer. Any help greatly appreciated.

Regards.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duankuiyuant3940 duankuiyuant3940 8年前

    You can send the parameter like this :

    function myCall() {
        var request = $.ajax({
            url: "ajax.php?param1=" + 'parameter',
            type: "GET",            
            dataType: "html"
        });
    
        request.done(function(msg) {
            $("#divholder").html(msg);          
        });
    
        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });
    }
    

    And get the parameter with $_GET

    Or you can send the parameter with POST (look at data : Ajax jQuery)

    点赞 评论 复制链接分享
  • dou72260 dou72260 8年前

    With a get request just append it to the url.

    $.ajax({
        url : 'ajax.php?someVar=20',
        type : 'GET',
        dataType : 'html'
    )}
    

    You can also add it to the data property and jQuery will url encode your data and append it to the url string.

    $.ajax({
        url : 'ajax.php',
        type : 'GET',
        dataType : 'html',
        data : {
            someVar : 20
        }
    )}
    
    点赞 评论 复制链接分享

为你推荐