gpt4 book ai didi

javascript - 如何使用 SmartyStreets 将 AJAX POST 发送到 PHP 脚本以进行地址验证?

转载 作者:行者123 更新时间:2023-11-30 00:25:20 26 4
gpt4 key购买 nike

我正在尝试实现 SmartyStreets API 以通过表单验证地址:街道、城市和州。我已经在没有 AJAX 实现的情况下实现了,但是当我切换到 AJAX 实现时。这是行不通的?我阅读了使用 JSONP 的必要性,但我没有使用 AJAX 直接 POST 到 SmartyStreets API。相反,我发布到将验证的 PHP 脚本。我计划做其他事情,例如在后端缓存地址请求和经过验证的地址以及响应。我已经创建了一个域 key 来访问 SmartyStreets API,但我认为由于 CORS 政策,这仍然不起作用。

这是我的地址验证表:

<div class="container">
<h2>Validate US address</h2>
<form role="form" id="myForm" action="post_without_curl2-INPUT.php" method="POST">
<div class="form-group">
<label for="street">street:</label>
<input type="text" class="form-control" id="street" name="street" placeholder="Enter street">
</div>
<div class="form-group">
<label for="city">city:</label>
<input type="text" class="form-control" id="city" name="city" placeholder="Enter city">
</div>
<div class="form-group">
<label for="state">state:</label>
<input type="text" class="form-control" id="state" name="state" placeholder="Enter state">
</div>
<!--<div class="checkbox">-->
<!--<label><input type="checkbox"> Remember me</label>-->
<!--</div>-->
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>

<script>
// Attach a submit handler to the form
$( "#myForm" ).submit(function( event ) {

console.log("Submit form");

// Stop form from submitting normally
event.preventDefault();

// Send the data using post
var posting = $.post( "post_without_curl2-INPUT.php", $( "#myForm" ).serialize() );

// Put the results in a div
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );
});
});
</script>

这是我的 PHP 脚本,用于通过 AJAX 将我的地址发布到:

<?php
// Your authentication ID/token (obtained in your SmartyStreets account)
$authId = urlencode("authID");
$authToken = urlencode("authToken");

// Your input to the API...
$addresses = array(
array(
"street" => $_POST['street'],
"city" => $_POST['city'],
"state" => $_POST['state'],
"candidates" => 1
);

// LiveAddress API expects JSON input by default, but you could send XML
// if you set the Content-Type header to "text/xml".
$post = json_encode($addresses);

// Create the stream context (like metadata)
$context = stream_context_create(
array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n"
."Content-Length: ".strlen($post)."\r\n",
"content" => $post
)
)
);


// Do the request, and we'll time it just for kicks
$start = microtime(true);
$page = file_get_contents("https://api.smartystreets.com/street-address/?auth-id={$authId}&auth-token={$authToken}", false, $context);
$end = microtime(true);


//// Show results
echo "<pre>";
echo "<b>Round-trip time (including external latency):</b> ";
echo (($end - $start) * 1000)." ms<br><br><br>"; // Show result in milliseconds, not microseconds

print_r(json_decode($page));
echo "</pre>";


?>

最佳答案

您的问题出在客户端代码中的这一行 JavaScript 中:

var content = $( data ).find( "#content" );

您似乎正在尝试对 SmartyStreets API 返回的数据执行 DOM 后代搜索。这是行不通的。 API 返回的是原始 JSON 数据。它看起来像这样:

[{"input_index":0,"candidate_index":0,"delivery_line_1":"1 Infinite Loop","last_line":"Cupertino CA 95014-2083","delivery_point_barcode":"950142083017","components":{"primary_number":"1","street_name":"Infinite","street_suffix":"Loop","city_name":"Cupertino","state_abbreviation":"CA","zipcode":"95014","plus4_code":"2083","delivery_point":"01","delivery_point_check_digit":"7"},"metadata":{"record_type":"S","zip_type":"Standard","county_fips":"06085","county_name":"Santa Clara","carrier_route":"C067","congressional_district":"18","rdi":"Commercial","elot_sequence":"0031","elot_sort":"A","latitude":37.33053,"longitude":-122.02887,"precision":"Zip9","time_zone":"Pacific","utc_offset":-8,"dst":true},"analysis":{"dpv_match_code":"Y","dpv_footnotes":"AABB","dpv_cmra":"N","dpv_vacant":"N","active":"Y"}}]

或者用你的 print_r(json_decode($page)); 命令格式化,它看起来像这样:

Array
(
[0] => stdClass Object
(
[input_index] => 0
[candidate_index] => 0
[delivery_line_1] => 1 Infinite Loop
[last_line] => Cupertino CA 95014-2083
[delivery_point_barcode] => 950142083017
[components] => stdClass Object
(
[primary_number] => 1
[street_name] => Infinite
[street_suffix] => Loop
[city_name] => Cupertino
[state_abbreviation] => CA
[zipcode] => 95014
[plus4_code] => 2083
[delivery_point] => 01
[delivery_point_check_digit] => 7
)

[metadata] => stdClass Object
(
[record_type] => S
[zip_type] => Standard
[county_fips] => 06085
[county_name] => Santa Clara
[carrier_route] => C067
[congressional_district] => 18
[rdi] => Commercial
[elot_sequence] => 0031
[elot_sort] => A
[latitude] => 37.33053
[longitude] => -122.02887
[precision] => Zip9
[time_zone] => Pacific
[utc_offset] => -8
[dst] => 1
)

[analysis] => stdClass Object
(
[dpv_match_code] => Y
[dpv_footnotes] => AABB
[dpv_cmra] => N
[dpv_vacant] => N
[active] => Y
)

)

)

如您所见,这不是您可以使用 jQuery 的东西 .find()功能开启。

您的代码已经可以满足您的要求。您的表单 POST 到 PHP 脚本并返回来自 SmartyStreets API 的响应。

恭喜。现在您只需处理返回的数据。

我可以建议您从更改此开始:

var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );

对此:

//var content = $( data ).find( "#content" );
$( "#result" ).empty().append( data );

关于javascript - 如何使用 SmartyStreets 将 AJAX POST 发送到 PHP 脚本以进行地址验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com