javascript
  • php
  • jquery
  • ajax
  • forms
  • 2016-10-01 128 views 1 likes 
    1

    添加參數的形式行動,我有以下形式沒有AJAX如何在阿賈克斯

    echo " 
    
    <form action='upload_Comment.php?post_id=$post_id' method='post' id='comments'> 
    
    <textarea class='form-control' name='comment' rows='1'></textarea> 
    
    <input type='submit' name='post_comment'> 
    </form> 
    
    
        "; 
    

    工作正常,但我需要使用Ajax來阻止該網頁的表單提交時重裝。

    $(document).ready(function(){ 
        $('#comments').on('submit', function(e) { 
        e.preventDefault(); 
    
        $.ajax({ 
         url: "upload_comment.php?post_id= + post_id ", 
         type: "POST", 
         data: new FormData(this), 
         dataType : 'json', 
         contentType: false, 
         processData: false, 
         success : function(data){     
               console.log(data); 
    
             }, 
             error: function(){alert('Error!')} 
        }) 
    
        }); 
    }); 
    

    我需要一種方法來我每次提交新文章時,通過$ POST_ID參數值和POST_ID對每個崗位獨特。可以有人請幫助我如何以ajax形式傳遞該post_id參數url

    +0

    如果它是一個服務器端的變量,將其放置在一個隱藏的輸入,而不是行動的查詢字符串 – adeneo

    +0

    我曾嘗試在隱藏字段中傳遞$ post_id值,但它只拾取數據庫中的第一個帖子ID,並非特定於發佈提交 – chris

    +0

    您可能想嘗試給會話變量。通過在顯示錶單之前在會話var中設置發佈ID,並直接在處理程序中拾取它,upload_comment.php而不使用查詢字符串。 – nocturns2

    回答

    0

    您不應該混合發送POST和GET請求,因爲GET用於GET信息,不能將其傳入。 您的代碼可能應該是這樣的:

    var fData = new FormData(this); 
    fData.append('post_id', post_id); 
    

    而且,閱讀本:HTTP POST with URL query parameters -- good idea or not?

    "upload_comment.php?post_id= + post_id " 
    

    應該像這樣(嚴重的是,不這樣做):

    "upload_comment.php?post_id=" + post_id 
    
    0

    以隱藏費爾德和assifn的帖子ID的價值到它

    <textarea class='form-control' name='comment' rows='1'></textarea> 
    <input type="hidden" value="<?=$post_id;?>" id="postId"> 
    <input type='submit' name='post_comment'> 
    </form> 
    

    和JS代碼將

    $(document).ready(function(){ 
    $('#comments').on('submit', function(e) { 
    e.preventDefault(); 
    var post_id =$('#postId').val(); 
    $.ajax({ 
        url: "upload_comment.php?post_id=" + post_id, 
        type: "POST", 
        data: new FormData(this), 
        dataType : 'json', 
        contentType: false, 
        processData: false, 
        success : function(data){     
              console.log(data); 
    
            }, 
            error: function(){alert('Error!')} 
    }) 
    
    }); 
    }); 
    
    +0

    我試過這個,但是$ post_id的隱藏值總是被選爲1,並且每個表單提交的帖子ID都不同,因爲它在循環中 – chris

    +0

    這是我的錯誤url:「upload_comment.php?post_id =」+ post_id而不是網址:「upload_comment.php?post_id = + post_id」 –

    相關問題