简单修改AJAX脚本,将返回的输出赋值,而不是打印到文本框中
Easy modification to AJAX script to assign the returned output in a value instead of printing it in textbox
我使用以下脚本
<script>
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL)
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
document.getElementById('cur_code').value=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:'n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
使用AJAX获取一些国家的货币,基于下拉值。
<select id="termid" class="selectfield" onChange="getCurrencyCode('find_ccode.php?country='+this.value)">
find_ccode.php 是
$country=$_REQUEST['country'];
switch($country)
{
case "1" :
echo "USD";
break;
case "2" :
echo "GBP";
break;
case "3" :
echo "NPR";
break;
}
我的文本框是
<input type="text" name="cur_code" id="cur_code">
我想要的是将国家的货币代码分配到PHP变量中,并在每次更改时回显它。如何做到这一点?
谢谢
有几种方法可以做到这一点:
-
存储在PHP会话中。你可以这样写find_ccode。php
-
使用PHP将其存储在cookie中。还是在find_ccode。php
-
使用JavaScript将其存储在cookie中。您可以在ajax响应处理程序中执行此操作。
如果你坚持选择1或2,你就会得到这样的伪代码:
$currCode = $.cookie('currcode');
一旦页面被加载,你就不能再在该页面上运行php代码,这是使用ajax的部分原因,它允许你从另一个文件中运行php代码,并在现有页面上使用它(使用javascript)。
如果你不喜欢把结果放在一个文本框里,你可以把它放在任何其他有id的html标签里,比如一个表格单元格,一个div,一个span等等。
你只需写innerHTML=而不是value=
document.getElementById('thisdiv').innerHTML=req.responseText;
如果你使用jQuery,为什么要自定义HTTPRequest呢?
<select id="termid" class="selectfield" onChange="getCurrencyCode(this.value)"><option>...</option></select>
<input type="text" name="cur_code" id="cur_code">
<script type="text/javascript">
function getCurrencyCode(setCountry){
$.get('find_ccode.php', { country: setCountry }, function(data) {
$('#cur_code').val(data);
});
}
</script>
后来编辑:则find_ccode.php
可以为
session_start();
$country=$_REQUEST['country'];
switch($country)
{
case "1" :
echo "USD";
$_SESSION['currency'] = 'USD';
break;
case "2" :
echo "GBP";
$_SESSION['currency'] = 'GBP';
break;
case "3" :
echo "NPR";
$_SESSION['currency'] = 'NPR';
break;
}
相关文章:
- 文本框不是从Javascript/Asp.net中的对话框中打印出来的
- 正在打印图表上的文本
- 如何在php中创建一个函数,该函数与文本区域一起工作,通过输入类似[color:red]的内容来打印具有等效颜色的文本
- 如何在html中打印选择文本
- 如何按骨干.js打印“此”列表项的文本
- 如何使用xpath和Javascript执行器打印文本
- 如何在php中使用echo来在html中打印文本
- 无法在所有页面中打印类似水印的背景文本
- 将所有单选按钮的值打印到文本区域
- 使用javascript/jquery打印文本文件的内容
- 单击时更改路径颜色时打印文本
- Javascript在列中打印文本
- javascript中的打印函数不是打印文本框值
- 试图获得按钮来激活将打印文本的功能
- 通过AJAX调用Perl Script来打印文本文件的内容
- VB.net如何直接打印文本客户端
- 如何在php中打印文本框值
- 如果当前值不是数组中的值,则打印文本
- 如何从UIWebView打印文本到JavaScript表单
- 在Canvas中使用setTimeout从数组中打印文本