当使用一个提交按钮Ajax调用不起作用按钮、不起作用、Ajax

2023-09-10 14:38:41 作者:ゝ回忆在黑夜里泛起涟漪﹌

我想用下面的API获取的实时汇率。

I'm trying fetch a live currency rate using the following API.

"http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj"

当我点击一个按钮,它就会提醒率和工作得很好。我用下面的Ajax code。

When I click on a button, it alerts the rate and works just fine. I'm using the following Ajax code.

<script type="text/javascript" language="javascript">
    function testCurrencyRate()
    {
        $.ajax({
                datatype:"html",
                type: "GET",
                url: "ajax/LiveCurrencyRate.php",
                data: "t="+new Date().getTime(),
                success: function(response)
                {       
                    alert(response);                    
                },
                error: function(e)
                {
                    alert('Error while fetchig the live currency rate.');                       
                }
            }); 
    }
</script>

在Ajax请求转到 LiveCurrencyRate.php 页面,该页面如下。

The Ajax request goes to the LiveCurrencyRate.php page which is as follows.

$url="http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj";               
$result = file_get_contents($url);
echo $result;   

&LT;形式GT;&LT; /表&GT; 包含这时候点击,使唯一的按钮在这个URL Ajax请求 AJAX / LiveCurrencyRate.php

and the <form></form> which contains the only button which when clicked makes an Ajax request on this URL ajax/LiveCurrencyRate.php.

<form id="testForm" name="testForm" action="" method="post">    
    <input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test" onclick="testCurrencyRate();"/>
</form>

一切都很好。然而,问题就出现了,当我改变从按钮类型TYPE =按钮 TYPE =提交,它不工作。在阿贾克斯功能的错误部分的警告框显示警告框只是一会儿,突然消失。我找不到任何合理的原因,可能prevent没有完成这一要求。同样的事情在我的previous项目为我工作,但我是用 XMLHtt prequest 制作Ajax请求。这是怎么回事错在这里?

Everything is fine. The problem however arises when I change the button type from type="button" to type="submit", it doesn't work. The alert box in the error part of the Ajax function shows the alert box just for a while and all of a sudden it disappears. I can't find any reasonable cause that may prevent this request from being completed. The same thing worked for me in my previous project but I was using XMLHttpRequest for making Ajax requests. What's going wrong here?

推荐答案

TYPE =提交使Web浏览器通过一个回发(提交表单,因为你的方法属性设置为POST),这会导致页面刷新。该动作的属性&LT;形式GT; 标记决定了数据被发送到,然后将该页面加载与提供的数据。发生这种情况时,页面上的所有JavaScript的终止,因为你有效地将不同的页面或重装当前的。

type="submit" causes the web browser to submit the form via a postback (because your method attribute is set to "POST"), which causes the page to refresh. The action attribute of the <form> tag determines where the data gets sent to, and then that page loads with the data provided. When this happens, all javascript on the page terminates because you are effectively going to a different page or reloading the current one.