SmartyStreets API を実装して住所 (通り、市、州) をフォームから検証しようとしています。私はAJAX実装なしで実装しましたが、AJAX実装に切り替えると. それは動作しません?JSONP を使用する必要性について調べましたが、SmartyStreets API に直接 POST するために AJAX を使用していません。代わりに、検証する PHP スクリプトに投稿しています。アドレス リクエストをキャッシュし、バックエンドで検証済みのアドレスをレスポンスとともにキャッシュするなど、他のことを行う予定です。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>
これは、私のアドレスを AJAX POST するための私の PHP スクリプトです。
<?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>";
?>