2013-10-20 145 views
0

我想用jQuery发送发布数据到我的发布数据文件处理程序postinfo.php,但到目前为止我可以做到这一点。发送HTML表单发布数据到Jquery文件?

这里是我的post.php中代码:

<HTML> 
<head> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
</head> 
<script type="text/javscript"> 
$('#form_id').on('submit', function(e){ 
    e.preventDefault(); 
    $.ajax({ 
     type: "POST", 
     url: "http://www.vemvo.com/test/postinfo.php", 
     data: $(this).serialize(), 
     success: function() { 
     alert('success'); 
     } 
    }); 
}); 
</script> 
<form method="post" id="form_id"> 
<input type="text" name="ime"> 
<input type="submit" id="submit" name="submit" value="Send"> 
</form> 

您可以在这里看到的页面:http://www.vemvo.com/test/post.php

这里是我的postinfo.php代码:

<?PHP 

$ime = $_POST['ime']; 

echo "Your name is $ime"; 
?> 

这里位于postinfo.php - http://www.vemvo.com/test/postinfo.php

那么,我的错误和我如何才能使它工作? 现在它不发送数据,也不给我成功警报。

+0

http://www.johnboy.com/scripts/simple-jquery-form-without-page-refresh/contact.php – Seazoux

+0

裹$( '#form_id')上(” (){...}) – mplungjan

回答

0
  1. 您必须阐明text/javascript正确

  2. 您需要分配负载事件处理

  3. 不应该有任何需要返回false张贴在这里其他一些人

  4. 从不要求任何形式的提交

  5. Wra p你的身体标记

  6. 使用正确的DOCTYPE

  7. 对于html文档,你可以看看uploadify或How can I upload files asynchronously?

为点1

固定码6

<!DOCTYPE html> 
<html> 
<head> 
<title>Test Ajax</title> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script type="text/javascript"> 
$(function(){ 
    $('#form_id').on('submit', function(e){ 
     e.preventDefault(); 
     $.ajax({ 
     type: "POST", 
     url: "./postinfo.php", 
     data: $(this).serialize(), 
     success: function() { 
     alert('success'); 
     } 
    }); 
    }); 
}); 
</script> 
</head> 
<body> 
    <form method="post" id="form_id"> 
    <input type="text" name="ime"> 
    <input type="submit" value="Send"> 
    </form> 
</body> 
</html>  
+0

我试过了你的代码,但它没有给出成功警报。我认为这不是发送数据太多.. –

+1

请不要叫任何名称=提交! – mplungjan

+0

你是什么意思?我改变了我的代码,看起来和你给我的完全一样,但它没有提供成功警报。在这里你可以看到它 - http://vemvo.com/test/post.php –

2

您的jQuery选择器不会找到该表单,因为选择器在DOM中存在form标记之前正在运行。尝试它包裹在jQuery的功能等待文件准备就绪:

$(function() { 
    $('#form_id').on('submit', function(e){ 
     // the rest of your code 
    }); 
}); 

它也可能是一个好主意,return false末,进一步打压表单的默认发布操作:

e.preventDefault(); 
$.ajax({ 
    type: "POST", 
    url: "./postinfo.php", 
    data: $(this).serialize(), 
    success: function() { 
    alert('success'); 
    } 
}); 
return false; 

当前表单是正常发布的。由于AJAX处理程序从不附加(因为选择器执行时元素不存在),它只是执行一个普通的文档级表单文章。由于form标记中没有指定action属性,因此该页面默认发布到自身。这只是回应当前页面。

编辑:你也有一个错字可以阻止浏览器在所有执行JavaScript代码:

<script type="text/javscript"> 

你错过了第二个“一”。这应该是:

<script type="text/javascript"> 
+0

所以我必须改变,以便将数据发布到./postinfo.php? 我的整个代码的外观如何? –

+0

无需返回false! – mplungjan

+0

@TonnyStruck:正如我的建议,你需要将你的jQuery代码包装在'$(function(){...});'中。目前你的代码在* form元素存在之前执行*。 (注意你的JavaScript块是如何在form元素之上的,它马上内联执行,所以它在form元素已知之前执行。)将它包装在jQuery函数中会导致它不会执行,直到整个文档为止准备。 – David