【发布时间】:2012-10-04 02:54:02
【问题描述】:
我正在尝试使用以下 API 获取实时汇率。
"http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj"
当我点击一个按钮时,它会提醒费率并且工作得很好。我正在使用以下 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>
Ajax 请求转到LiveCurrencyRate.php 页面,如下所示。
$url="http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj";
$result = file_get_contents($url);
echo $result;
和<form></form>,它包含唯一的按钮,当单击该按钮时,该按钮会在此 URL ajax/LiveCurrencyRate.php 上发出 Ajax 请求。
<form id="testForm" name="testForm" action="" method="post">
<input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test" onclick="testCurrencyRate();"/>
</form>
一切都很好。然而,当我将按钮类型从type="button" 更改为type="submit" 时,问题就出现了,它不起作用。 Ajax 函数错误部分的警告框只显示了一段时间,然后突然消失了。我找不到任何可能阻止此请求完成的合理原因。在我之前的项目中,同样的事情对我有用,但我使用XMLHttpRequest 来发出 Ajax 请求。这里出了什么问题?
【问题讨论】:
-
可能是因为你需要在表单的提交动作而不是按钮点击动作中处理它
-
submit 触发表单元素的默认行为(包括页面重新加载)。这很容易预防,应该已经有很多关于这个的问题了。
标签: javascript jquery ajax