doujiao6507
2016-07-20 16:40
浏览 42
已采纳

将Jquery变量传递给php url

I have a jquery function that looks like this:

$('.dislike_box a').click(function(event){
    event.preventDefault();
    var title = $(this).data('title');
    alert(title);
    $.ajax({
    url: 'vote.php?vote=dislike&title=title', 
    success: function(result){
        $('.dislike_box p.vote_text').text('Dont Like it.');
    }});
});

My issue is when I alert the title variable it is correct but when I pass it to the php script to be put into the database the php script uses the $_GET[] method but puts the literal string "title" into the database instead of the variable value.

Answer: Thanks to @Ivan

 url: 'vote.php?vote=dislike&title='+title, 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dptpn06684 2016-07-20 16:43
    已采纳

    The variable you are sending via AJAX isn't a variable but the string 'title'. Instead use + to add the variable in the URL.

    $('.dislike_box a').click(function(event){
        event.preventDefault();
        var title = $(this).data('title');
        alert(title);
        $.ajax({
        url: 'vote.php?vote=dislike&title='+title, 
        success: function(result){
            $('.dislike_box p.vote_text').text('Dont Like it.');
        }});
    });
    

    To retrieve the js variable in PHP file :

    <?php
    
    if(isset($_REQUEST['title'])) {
        $title = $_REQUEST['title'];
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongyisa6254 2016-07-20 16:50

    You are sending the literal string title in your AJAX call. You would need to actually put your title value into your URL.

    A better solution would be, if you make jQuery escape the values, so you don't need to worry, if your title contains special characters like ?, &, =, etc.

    $('.dislike_box a').click(function(event){
        event.preventDefault();
        var title = $(this).data('title');
        alert(title);
        $.ajax({
            url: 'vote.php',
            data: {
                vote: 'dislike',
                title: title
            }, 
            success: function(result){
                $('.dislike_box p.vote_text').text('Dont Like it.');
            }
        });
    });
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题