[英]Issue on Posting HTML Content Using jQuery - Ajax Post Method
我正在嘗試使用jquery ajax將div部分發布到新頁面:
<!DOCTYPE html>
<body>
<div id="edit_content">
<p>This is a test</p>
</div>
<a href="out.php" id="submit_script">Submit</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var htmlData = $('#edit_content').html();
$.post('out.php', {'html': htmlData },function(){
});
});
</script>
</body>
</html>
在out.php
頁面中我有:
<?php
$content = $_POST['html'];
echo $content;
但是當我運行代碼時,我收到此錯誤:
注意:未定義的索引:第2行的G:\\ Apps \\ out.php中的html
能不能讓我知道為什么會這樣,我怎么能阻止它?
您的$.post
函數在數據字段中有拼寫錯誤,請嘗試以下操作:
$.post('out.php', {html: htmlData }, function(response){
由於您要發送對象,因此該密鑰不需要引號。
或者更好,但是你的所有數據都在你的帖子中引用它們:
var postData = {html: $('#edit_content').html() }
$.post('out.php', postData, function(response){
您的代碼按原樣運行 - 至少就帖子而言。 為了說明這一點,將其更改為以下內容(唯一的變化是實際上對ajax請求的響應做了一些事情):
<!DOCTYPE html>
<body>
<div id="edit_content">
<p>This is a test</p>
</div>
<a href="out.php" id="submit_script">Submit</a>
<div id="out"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var htmlData = $('#edit_content').html();
$.post('out.php', {'html': htmlData }, function(data){
$('#out').html(data);
});
});
</script>
</body>
</html>
我認為你需要解釋你想要做什么(或者你期望看到的)。 正如您的代碼所示,您一旦頁面加載(在文檔就緒)但是沒有對響應做任何事情,就會運行ajax請求。 然后,您有一個指向out.php的鏈接( <a href="out.php" id="submit_script">Submit</a>
)。 當您點擊鏈接時,您是否希望在out.php中看到結果? 如果是這樣,那就不會發生。 發生的事情是,當頁面加載時,它會使用post數據向out.php運行請求並獲得響應(然后忽略)。 當您單擊該鏈接時,您會在沒有發布數據的情況下向out.php運行新請求 ,因此您什么都看不到。
如果我猜對了,那么你想用點擊鏈接觸發的表單提交替換鏈接(首先獲取數據)。 就像是
<!DOCTYPE html>
<body>
<div id="edit_content">
<p>This is a test</p>
</div>
<a href="#" id="submit_script">Submit</a>
<form action="out.php" method="post" id="out-form" style="display: none;">
<input type="hidden" id="hidden-html" name="html" value="" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('#submit_script').click(function(){
$('#hidden-html').val($('#edit_content').html());
$('#out-form').submit();
return false;
})
});
</script>
</body>
</html>
'html'數據未發布到您的php頁面。 將您的php文件更改為:
<?php
if(isset($_POST['html']))
{
$content = $_POST['html'];
echo $content;
}
?>
這應該可以阻止錯誤並至少指向正確的方向。 如果沒有更多代碼,我無法告訴您為什么沒有發布'html'數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.