[英]Cross Domain Ajax request using Jquery and Ajax to get a value from the server
I am trying to make an Ajax request from my localhost to a php file in the server. 我正在尝试从本地主机向服务器中的php文件发出Ajax请求。 As I am testing this, I am yet to do the real code in the PHP file.
在测试时,我还没有在PHP文件中执行真正的代码。 I just want the PHP file to get the posted value and echo the same.
我只希望PHP文件获取发布的值并回显相同的值。 After getting the response from the PHP file, I want to store it in a div.
从PHP文件获取响应后,我要将其存储在div中。
This works good when search.php in my localhost but throws an error 当我的本地主机中的search.php时,此方法工作良好,但抛出错误
XMLHttpRequest cannot load http://www.mysite.com/search.php .
XMLHttpRequest无法加载http://www.mysite.com/search.php 。 No 'Access-Control-Allow-Origin' header is present on the requested resource.
所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin 'null' is therefore not allowed access.
因此,不允许访问原始“空”。
Here is the very simple PHP file on the server which echo back what is posted. 这是服务器上非常简单的PHP文件,它回显所发布的内容。
HTML 的HTML
<form action='http://www.mysite.com/search.php' id='search-form' method='post'>
<input name='q' placeholder='Search' type='text' />
<button id='search-button' type='submit'><span>Search</span></button>
</form>
<div class="sample_code">Search Results</div>
<div id="result"></div>
Jquery jQuery的
$("#search-form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
term = $form.find('input[name="q"]').val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post(url, {
q: term
});
/* Put the results in a div */
posting.done(function(data) {
//var content = $(data).find('#content');
$("#result").empty().append(data);
});
});
A PHP file in the server to echo what is posted (search.php) 服务器中的一个PHP文件以回显所发布的内容(search.php)
<?php
$item = $_POST['term'];
echo $item;
?>
尝试使用“ jsonp”,但是它仅支持GET方法并且是DOM阻塞的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.