prototype.js ajax.request,prototypejs - Prototype JS framework for Ajax request - Stack Overflow

Firstly parameters needs to be an object like this.

parameters : {'zip': zip }

Or you can shortcut and put the parameter in the URL string, but lets focus on other problems you are going to run into.

You should probably use observers instead of the onblur attribute. It allows you to add as many event handlers to your elements as the browser has memory to handle. It also allows you to separate the javascript from the HTML and organize the observers together.

The $() method uses ids and not the names, so you need to add those attributes. This is why you are getting the other error that zip is not defined.

so

...snip...

Zip code: City

id = "city" size = "30" />

State

id = "state" size = "30" />

...snip...

and I would use JSON instead of doing comma splitting as its easier to handle more properties when you need to add them, and less prone to weird splitting errors

function getPlace(){

//getPlace() is an event handler so `this` points to the element being observed

new Ajax.Request("getCityState.php?zip="+this.getValue(),

onSuccess: function(request) {

var place = request.responseJSON;

$("city").value = place.city;

$("state").value = place.state;

},

onFailure: function(request) {

alert("Error - request failed");

}

}

document.observe('dom:loaded',function(){

$('zip').observe('blur',getPlace);

});

JSON output requires a little adjustment of your backend script

// getCityState.php

// Gets the form value from the "zip" widget, looks up the

// city and state for that zip code, and prints it for the

// form

$cityState = array("81611" => array("city" => "Aspen" ,"state" => "Colorado"),

"81411" => array("city" => "Bedrock" ,"state" => ", Colorado"),

"80908" => array("city" => "Black Forest","state" => "Colorado"),

"80301" => array("city" => "Boulder", "state" => "Colorado"),

"81127" => array("city" => "Chimney Rock", "state" => "Colorado"),

"80901" => array("city" => "Colorado Springs", "state" => "Colorado"),

"81223" => array("city" => "Cotopaxi", "state" => "Colorado"),

"80201" => array("city" => "Denver", "state" => "Colorado"),

"81657" => array("city" => "Vail", "state" => "Colorado"),

"80435" => array("city" => "Keystone", "state" => "Colorado"),

"80536" => array("city" => "Virginia Dale", "state" => "Colorado")

);

header("Content-type: application/json");

//isset() is a faster test than array_key_exists()

if(isset($cityState[$_GET['zip']])

{

print json_encode($cityState[$_GET['zip']]);

}

else

{

print "false";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值