简体   繁体   中英

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. As I am testing this, I am yet to do the real code in the PHP file. I just want the PHP file to get the posted value and echo the same. After getting the response from the PHP file, I want to store it in a div.

This works good when search.php in my localhost but throws an error

XMLHttpRequest cannot load http://www.mysite.com/search.php . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Here is the very simple PHP file on the server which echo back what is posted.

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);
        });
    });

A PHP file in the server to echo what is posted (search.php)

    <?php

    $item = $_POST['term'];
    echo $item;

    ?>

尝试使用“ jsonp”,但是它仅支持GET方法并且是DOM阻塞的。

Best solution for that post ajax to your php file then in php file use curl a link that will call data from another website.

echo curl response and catch that data.

I have used this method. Its working .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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