我在使用php和ajax从moz api获取数据时遇到问题。我希望用户能够输入一个网址,然后有一个替换divs html的函数。 hello.php来自Moz Api。我正在使用MAMP,我的代码如下:
<div class="container">
<h1>hello from gulp automation tool</h1>
<form method="post" action="">
<label for="url">Enter URL:</label><input value="" type="url" name="url" id="url"/>
<input type="submit" value="Get URL Metrics!"/>
</form>
<div class="info">
</div>
</div>
<script>
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var dataUrl = $('form input[type=url]').val();
$.ajax({
url: "hello.php",
type: "POST",
method: "POST",
dataType: 'json',
data: dataUrl,
success: function(response){
$('.info').html(
response[0].pda
);
}
});
});
});
</script>
以下是hello.php文件中的代码。
<?php
// Add your accessID here
$AccessID = 'mozscape-a034cdc391';
// Add your secretKey here
$SecretKey = '6ac62e3e6df3ad617c7cf3fef891df9d';
// Set the rate limit
$expires = time() + 300;
// Put each parameter on a new line.
$stringToSign = $accessID."\n".$expires;
// Get the "raw" or binary output of the hmac hash.
$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);
// Base64-encode it and then url-encode that.
$urlSafeSignature = urlencode(base64_encode($binarySignature));
// Add up all the bit flags you want returned.
// Learn more here: https://moz.com/help/guides/moz-api/mozscape/api-reference/url-metrics
$cols = "68719476736";
// Put it all together and you get your request URL.
$requestUrl = "http://lsapi.seomoz.com/linkscape/url-metrics/? Cols=".$cols."&AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSig nature;
// Put your URLS into an array and json_encode them.
$batchedDomains = array($_POST['data']);
$encodedDomains = json_encode($batchedDomains);
// Use Curl to send off your request.
// Send your encoded list of domains through Curl's POSTFIELDS.
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $encodedDomains
);
$ch = curl_init($requestUrl);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close( $ch );
$contents = json_decode($content);
print_r($contents);
?>