使用AJAX PHP的空白$ _ POST变种 [英] Blank $_POST var in PHP using AJAX
问题描述
所有我想要做的就是发送一个字符串,在HTML中,为PHP编写的脚本。我试了几种解决方案,包括制作一个HTML元素,并把它放在一个表格,然后通过表单(没有工作)。我不知道AJAX或PHP的基础知识,一切都只是一种正在通过什么我可以谷歌拼凑在一起。这里有一种方法我试图纠正这种情况:(的正则表达式替换第一行的文件,这是我的作品我试图foreach循环与分配变量$ _ POST [$键],我试着仅发送字符串与HTML希望。这会工作。我认为,问题就出在HTML,或在AJAX调用,因为我可以做的形式提交()的PHP文件,然后将它不过工作,这将改变浏览器的位置,该文件和显然与AJAX,那不是我想要的。任何人有任何的想法(除了JQuery的语法等)?
All I'm trying to do is send a string, in html, to a script written in PHP. I've tried several solutions, including making an html element and putting it in a form and then passing the form (didn't work). I don't know the basics of AJAX or PHP, everything is just kind of being pieced together via what I can google. Here's one way I trying to remedy the situation: (The regexp replaces the first line of the file, which I works. I tried foreach loops with assigning a variable to $_POST[$key], I tried sending just the string with html hoping that would work. I believe the problem lies in the HTML, or in the AJAX call, because I can make the form submit() to the .php file and then it works, however, that would change the browser location to that file and obviously with AJAX, that's not what I want. Anyone have any ideas (other than JQuery syntax)?
HTML
<form>
<input type="hidden" name="test" id="test" value="testString">
</form>
JavaScript的AJAX调用
JavaScript AJAX call
function sendString()
{
var data = document.getElementById("test");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', 'testing.php', true);
xhr.send(data);
}
PHP文件
PHP File
<?php
$line = $_POST['data'];
$file = 'test.txt';
file_put_contents($file,preg_replace('/^.+/',$line,file_get_contents($file),1));
?>
编辑:感谢您的答复,但非工作过。我想:
Thanks for the responses, but non have worked. I tried:
document.getElementById("test");
document.getElementById("test").value;
和 xhr.send(data.value);
and xhr.send(data.value);
所有这些工作。还是空白行。我也试图扩展的解决方案。
None of these worked. Still Blank lines. I also tried the extended solution.
推荐答案
您的问题就在这里:
var data = document.getElementById("test");
您正在创建一个引用您的html元素。您需要引用你的元素的值属性。
You're creating a reference to your html element. You need to reference the value property of your element.
var data = document.getElementById("test").value;
另外,你只发送值,而不是一个关键值对给服务器。因此, xhr.send(数据);
将只发送值。你的PHP脚本不会知道 $ _ POST ['数据']
是你的意思。您需要格式化 VAR数据
为
Also, you are only sending the value and not a key value pair to the server. So xhr.send(data);
will only send the value. Your PHP script won't know that $_POST['data']
is what you mean. You need to format var data
as
var data = "data=" + document.getElementById("test").value;
修改
要通过POST发送表单数据,则可能需要添加一些头信息。
To send form data via POST, you may need to add some header information.
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
这篇关于使用AJAX PHP的空白$ _ POST变种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!