使用Jquery和Ajax从服务器获取值的跨域Ajax请求

Cross Domain Ajax request using Jquery and Ajax to get a value from the server

本文关键字:Ajax 请求 服务器 Jquery 使用 获取      更新时间:2023-12-05

我正试图从本地主机向服务器中的php文件发出Ajax请求。在测试这一点时,我还没有在PHP文件中编写真正的代码。我只想让PHP文件获得发布的值,并返回相同的值。从PHP文件中获得响应后,我想将其存储在一个div.中

当在我的本地主机中搜索.php但抛出错误时,这效果很好

XMLHttpRequest无法加载http://www.mysite.com/search.php.不请求的上存在"Access Control Allow Origin"标头资源因此,不允许访问源"null"。

下面是服务器上一个非常简单的PHP文件,它会回显发布的内容。

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

     $("#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);
        });
    });

服务器中用于响应发布内容的PHP文件(search.PHP)

    <?php
    $item = $_POST['term'];
    echo $item;
    ?>

尝试"jsonp",但它只支持GET方法,并且是DOM阻塞。

ajax发布到您的php文件的最佳解决方案然后在php文件中使用curl链接,该链接将调用另一个网站的数据。

回波卷曲响应并捕获该数据。

我用过这种方法它正在工作