簡體   English   中英

如何使用ajax返回值

[英]How to return value using ajax

我有一個Ajax文件,其中已編寫代碼以接受來自user的值,然后將這些值在Ajax函數中采用,如下所示:

$(document).ready(function(){  
            $("#newsletterform").validate();  
            $('#Submit').click(function(){  
                var name = $('#newsletter_name').val();  
                var email = $('#newsletter_email').val();  
                 sendValue(email,name);  
            });  
            });

用於傳遞值並從其他文件獲取值的函數:

function sendValue(str,name){  
                $.post(  
                "newsletter/subscribe.php", //Ajax file  
                { sendValue: str,  
                  sendVal: name  
                },  
                function(data2){  
                    $('#display').html(data2.returnValue);  
                },  

    //How you want the data formated when it is returned from the server.
                "json"  
                );  
            }

然后將這些值傳遞到另一個名為“ subscribe.php”的文件,在其中寫入數據庫的插入代碼,然后再次將值返回給我的第一個ajax函數,如下所示:

echo json_encode(array("returnValue"=>$msg));  
The msg is ging to contain my message to be displayed.

但是現在,這在localhost上可以正常工作,我可以正確獲取返回值nad消息,但是當我將其上傳到服務器上時,這給我一個錯誤:

data2 is null
[Break on this error] $('#display').html(data2.returnValue);

這只會給返回值帶來錯誤,但是插入,發送郵件功能可以正常工作。
請為我提供一個好的解決方案,使我能夠無誤地返回返回值。
提前致謝。

如果它在您的開發站點上可行,我懷疑該錯誤出在您的PHP腳本中。 您的主機可能會運行一個沒有json_encode()的古老php版本。 只需手動調用腳本即可檢查其輸出。 如果需要POST,則可以編寫表格或使用FireBug將結果檢查到ajax調用中

如果沒有其他解釋,為什么會這樣,請嘗試以下操作:

$(document).ready(function(){  
        $("#newsletterform").validate();  
        $('#Submit').click(function(e){  // added the e paramenter
            var name = $('#newsletter_name').val();  
            var email = $('#newsletter_email').val();  
             sendValue(email,name);
            e.stop(); // dont submit the form normaly
        });  
}); 

如果您有螢火蟲,請將data2寫入其控制台,看看它是什么:

function(data2) {  
    console.log(data2);
    $('#display').html(data2.returnValue);  
}

另外,您可以使用firebug網絡面板查看您的php文件原始響應(如果有錯誤-您將在此處看到它)。

使用:

var response = $.ajax({
   type : "POST",
   url : "newsletter/subscribe.php",
   dataType : "json",
   async : false,
   data : "sendValue="+str+"&sendVal="+name
}).responseText;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM