【问题标题】:How to implement ajax and jquery into html如何在html中实现ajax和jquery
【发布时间】:2012-03-09 04:51:05
【问题描述】:

我之前问过一个问题,关于如何将显示/隐藏功能添加到 div 并在单击链接时准确呈现它。 (The original question) 我收到了一起使用 jquery 和 ajax 来执行此操作的答案。这是我收到的代码:

function unhide(){
    $('#id-of-showhide-div').css({'display','block'});
    $.ajax({
        url: 'http://api.microsofttranslator.com..', // your url to microsoft translator
        success: function(data) {
            $('#id-of-showhide-div').html(data);
        }
    });
}

现在因为我是新手,所以我不知道如何使用它。这是我尝试制作的 html,但它不起作用:

<script type="text/javascript">
function unhide(){
    $('#id-of-showhide-div').css({'display','block'});
    $.ajax({
        url: 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
        success: function(data) {
            $('#id-of-showhide-div').html(data);
        }
    });
}
</script>

<a href="javascript:unhide('a');">Show/Hide Value</a>
<div id="a">javascript:unhide('a');</div>

我的 microsofttranslator 链接输出了一些文本。我希望它仅在有人单击“显示/隐藏值”链接时才加载该 URL。它只需要加载一次。我的意思是当有人点击它时,它会被渲染和显示,当他再次点击它时,它会被隐藏,当他再次点击它时,它不会再次渲染它并从他第一次点击它时开始显示它。 顺便说一句,我的页面上有很多 div,所以每个 id 都必须是唯一的。

抱歉问题太长了。

谢谢

PS:如果api是在客户端完成的,也不会有问题。

【问题讨论】:

  • 您不会使用javascript:unhide('a') 调用该函数。你会使用onclick="unhide('a')"。

标签: jquery html ajax


【解决方案1】:

砰!这是一个完整的工作示例(尽管我正在访问 Twitter API 状态页面)。 cmets 应该回答你所有的问题。您需要做的就是将锚标签中的链接更改为您想要的链接。

<!doctype html>
<html>
    <head>
        <title>My Rockin' Answer</title>

        <style type="text/css">
            #contents{
                margin-top:20px;
                border:1px solid #FF0000;
                display:none;
            }
        </style>

    </head>
    <body>

        <a href="https://api.twitter.com/1/help/test.json" 
           title="Show / Hide" class="show" id='link'>Show Twitter API Status</a>

        <!-- Here is the DIV that we're putting the ajax content into -->
        <!-- Notice that it's hidden above in the CSS -->
        <div id="contents"></div>

        <!-- Include jQuery from the jQuery CDN -->
        <!-- Always put your Javascript at the end of the file because it -->
        <!-- may prevent some of the other content from loading while it's -->
        <!-- fetching the javascript from the CDN -->
        <script src='http://code.jquery.com/jquery-latest.min.js'></script>
        <script type='text/javascript'>

          // This waits until the document is completely done loading
          $(document).ready(function(){

            // The code inside this function gets 
            // called when the user clicks the link
            $('#link').click(function(e){

                // This prevents the link from going to it's href
                // If we don't have this, none of the following 
                // javascript will be executed
                e.preventDefault();

                // Check to see if we're displaying the ajax content...
                if($(this).hasClass('show')){

                    // Since we're not showing the ajax content, grab it
                    $.ajax({
                        url     : $(this).attr('href'),  // Use the value we have in the href attribute
                        success : function(response){    // Execute the code in here when we successfully get the content back
                            $('#link').removeClass('show').addClass('hide'); // Indicate that we are showing the ajax content
                            $('#link').html('Hide Twitter API Status');      // Change the link's text
                            $('#contents').html(response);                   // Append the ajax content into our hidden div
                            $('#contents').show();                           // Show the hidden div
                        }
                    });

                } else {
                    // We are already showing the ajax content so...

                    // Indicate that we are no longer showing the ajax content
                    $(this).removeClass('hide').addClass('show');

                    // Change the link text
                    $(this).html('Show Twitter API Status');        

                    // Hide the ajax content
                    $('#contents').hide();
                }
            });
          });
        </script>
    </body>
</html>

【讨论】:

  • 你用的是什么浏览器?你在 Javascript 控制台中遇到了什么错误?
  • 我将 --api.twitter.com/1/help/test.json-- 更改为 --api.microsofttranslator.com/V2/Ajax.svc/… 并且当我单击链接并且 JS 控制台没有显示任何内容时没有任何反应。
  • 您使用的是哪个浏览器?我刚刚切换了 URL,它对我来说很好用。如果您使用的是 Chrome,您可能会收到一条错误消息:XMLHttpRequest cannot load http://api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=9CF5D9435A249BB484EC6DB50FFFB94C6733DEFB&amp;from=en&amp;to=de&amp;text=Hello--. Origin null is not allowed by Access-Control-Allow-Origin.,但您可以按照此处的说明进行覆盖:stackoverflow.com/questions/4742467/…
  • 我正在使用火狐。当我点击它时,什么也没有发生。我的 html 页面仅包含此代码,其 url 已更改。我必须在 html 中添加其他内容吗?
  • 您在使用同源策略 (developer.mozilla.org/en/Same_origin_policy_for_JavaScript) 时遇到问题。我保证,如果您将此脚本上传到测试服务器或使用禁用了同源策略的浏览器进行尝试,它会起作用。
【解决方案2】:

试试这个:

<script type="text/javascript">
    function toggleDiv(id){
        if ($('#' + id).html() == '') {
            $.ajax({
                url: 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
                success: function(data) {
                    $('#' + id).html(data);
                },
                error: function() {
                    $('#' + id).html('The resource could not be loaded');
                }
            });
        }

        $('#' + id).toggle(); // Toggle div visibility
    }
</script>

<a href="#" onclick="toggleDiv('a')">Show/Hide Value</a>
<div id="a" style="display:none"></div>

【讨论】:

  • 它也不起作用。当我单击“显示/隐藏”值时,什么都没有发生。
  • 如果你查看JS控制台(CTRL+SHIFT+J),它注册了什么错误?
  • 它说,$ 没有定义。第 3 行
  • 啊。这可能是因为您没有正确加载 jQuery。尝试在标题中包含此内容:&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;
  • 我刚刚在我的评论中编辑了代码以包含 ajax 请求的错误处理程序——现在,即使你正确加载了 jQuery,它也不会工作,因为网址不是真实的。
猜你喜欢
  • 2012-09-27
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多