我有以下代码,它从 Cardspring 服务器获取响应并尝试将其发送到我们的站点以存储在我们的数据库中。我无法让 ajax 正常工作。当我查看 heroku 服务器日志时,似乎 ajax 没有向我们的服务器发送 POST —— ajax 请求没有日志条目。ajax 代码如下所示:
<script type="text/javascript">
$(document).ready(function()
{
$('#contactform').submit(function(event) {
$('.submit-button').attr('disabled', 'disabled');
cardSpringResponseHandler = function(response){
if((typeof response.error) != "undefined")
{
var error = response.error;
var reason = response.reason;
alert(error + ' ' + reason);
}
else
{
alert(response.token + ' ' + response.last4 + ' '+ response.brand + ' ' + response.brand_string + ' ' + response.expiration);
alert('Thank you, your card is registered!');
$.ajax({
type: 'POST',
url:'www.url.com/me',
async: false,
data: {"token": response.token,"last4": repsonse.last4,"brand": response.brand,"brand_string":response.brand_string,"expiration": response.expiration}.serialize(),
error: function () {
alert('Error');
}
});
}
alert('Hello 2');
};
alert('adding card');
CardSpring.addCard(cardSpringResponseHandler
, {
publisher_id : '{{ CARDSPRING_APP_ID }}',
security_token : '{{ securityToken }}',
timestamp : '{{ timestamp }}',
hmac : '{{ digestedHash }}'
}, {
card_number : $('.card-number').val(),
exp_month : $('.expiration-month').val(),
exp_year : $('.expiration-year').val(),
user_id : '{{ csid }}'
}, "all");
alert('card added');
return false;
});
});
</script>
这是 urls.py 的片段,用于显示 url:
url(r'^me/$', accountInfo),
这是服务器端代码的外观,作为 django 视图:
def accountInfo(request):
#after CS.addCard is sucessful, this adds the credit card Token to our DB...
print request.method
if request.method == "POST":
print "in account info"
print "expiration = " ,
#print request.POST['expiration']
print "request ="
print request
try:
cardToAdd = Cards(csID = request.COOKIES.get('csID'),token = request.POST['token'], last4 = request.POST['last4'], cardType = request.POST["brand"] ,typeString = request.POST['brand_string'],
expDate = request.POST['expiration'])
cardToAdd.save();
json_data = json.dumps({"HTTPRESPONSE":"sucess"})
return HttpResponse(json_data, mimetype="application/json")
except:
json_data = json.dumps({"HTTPRESPONSE":"fail"})
return HttpResponse(json_data, mimetype="application/json")
初始打印 request.method 在第一次加载页面时运行,method = GET。服务器没有打印出任何其他请求,这让我觉得 ajax 代码没有运行
警报(至少其中一些)确实发生了。它们总是按以下顺序出现:
- 加卡
- 已添加卡
- response.token、response.last4 等
- 谢谢,您的卡已添加
有谁知道发生了什么?谢谢你的帮助——我对 ajax 和 javascript 非常生疏