简体   繁体   English

使用POST和AJAX获取数据

[英]Get data using POST and AJAX

I'm trying to send some data in my server asynchronously using AJAX. 我正在尝试使用AJAX在服务器中异步发送一些数据。 I need to send the data using the POST method because the data sent are quite many characters and by using GET the created URL will be too big. 我需要使用POST方法发送数据,因为发送的数据很多字符,并且使用GET创建的URL将太大。 Well that's not a problem, but for aesthetically reasons I would rather have small URLs. 嗯,这不是问题,但是出于美学原因,我宁愿使用较小的URL。 In order to do so I used the solution (question) explained here . 为此,我使用了此处说明的解决方案(问题)。

My Javascript code sending the data is: 我发送数据的Javascript代码是:

   var code = "code=" + document.getElementById("code_area").value;
   xmlhttp.open("POST", "run_code.php", true);
   xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   xmlhttp.send(code);

The above code is executed when I click a button, but then the URL changes to this: localhost/code.php?code=datadatadatadatadatadatadatadatadatadatadatadatadatadata which seems is no different of using GET instead (my URL has become quite big). 上面的代码在我单击按钮时执行,但是URL更改为: localhost/code.php?code=datadatadatadatadatadatadatadatadatadatadatadatadatadata这似乎与使用GET没什么不同(我的URL变得很大)。 I used POST , not GET but still data seems to get transmitted by the URL. 我使用POST ,而不是GET但似乎数据仍通过URL传输。 Any ideas why is this happening? 任何想法为什么会这样?

You could do that much more easily using jQuery. 您可以使用jQuery更轻松地做到这一点。

$.post("run_code.php", { code: $("#code_area").val() });

Links: 链接:

Way easier with jquery... 用jQuery更容易...

$.post( 'yoururlhere.com/phppage',
        {code:$("#code_area").val()},
        function(responseData){
            // responseData is the echo'd data set from your php page
        }, 'json'
);

the data within { } are the post KV pairs {}中的数据是后KV对

responseData is the dataset echo'd back from php responseData是从php回显的数据集

The problem after all was that I was using a submit input field in my HTML page like this: 毕竟问题是我在HTML页面中使用了提交输入字段,如下所示:

<input type="submit" />

which when used changed (refreshed) the URL. 使用时会更改(刷新)URL。

By using: 通过使用:

<input type="button" />

the problem has been fixed. 该问题已解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM