weixin_33712881 2015-04-16 08:39 采纳率: 0%
浏览 16

JavaScript答案

(function() {
    main();
    function main() { 
        jQuery(document).ready(function($) { 
            $.ajax({
                type: 'post',
                url: 'http://example.com/search.php',
                data: { value: '123' },
                cache: false,
                success: function(returndata) {
                    $('#widget').html(returndata);
                }
            });
        });
    }
})(); 
<script src="http://example.com/widget.js" type="text/javascript"></script>
<div id="widget"></div>

When I paste widget on my site, it works perfectly and I get answers who is in div "widget" but if I paste this:

<script src="http://example.com/widget.js" type="text/javascript"></script>
<div id="widget"></div>

for another page it's not working. Can anyone help?

  • 写回答

1条回答 默认 最新

  • weixin_33739646 2015-04-16 09:15
    关注

    As of your comment, you are experiencing Cross domain restrictions (Same-origin policy). A workable solution for this is to serve your content from "search.php" as jsonp instead.

    <?php
    
    header('content-type: application/json; charset=utf-8');
    $searchResults= array("Article 1", "Article 2", "Article 3");
    echo $_GET['callback'] . '('.json_encode($searchResults).')';
    
    ?>
    

    In your jQuery $.ajax, you should set the dataType to "jsonp, and perhaps set the parameter crossDomain to true aswell.

    (function() {
        main();
        function main() { 
            jQuery(document).ready(function($) { 
                $.ajax({
                    type: 'post',
                    dataType: 'jsonp',
                    crossDomain: true, // Shouldent be neccesary.
                    url: 'http://example.com/search.php',
                    data: { value: '123' },
                    cache: false,
                    success: function(returndata) {
                        $('#widget').html(returndata);
                    }
                });
            });
        }
    })(); 
    

    Hope it works out for you.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog