使用提交按钮时,ajax调用不起作用

Tin*_*iny 1 javascript ajax jquery

我正在尝试使用以下API获取实时汇率.

"http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj"
Run Code Online (Sandbox Code Playgroud)

当我点击一个按钮时,它会提醒率并且工作得很好.我正在使用以下Ajax代码.

<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>
Run Code Online (Sandbox Code Playgroud)

Ajax请求转到LiveCurrencyRate.php如下页面.

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

并且<form></form>它包含唯一的按钮,当单击该按钮时,会在此URL上发出Ajax请求ajax/LiveCurrencyRate.php.

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

一切都好.然而,问题出现了,当我从改变按钮类型type="button"type="submit",这是行不通的.Ajax函数的错误部分中的警告框只显示警报框一段时间,突然它消失了.我找不到任何可能阻止此请求完成的合理原因.在我之前的项目中,同样的事情对我有用,但我用它XMLHttpRequest来制作Ajax请求.这里出了什么问题?

Ste*_*unt 10

type="submit"导致Web浏览器通过回发提交表单(因为您的method属性设置为"POST"),这会导致页面刷新.标记的action属性<form>确定数据发送到的位置,然后该页面加载所提供的数据.发生这种情况时,页面上的所有javascript都会终止,因为您实际上是在转到其他页面或重新加载当前页面.