我试图通过带有ajax的帖子将数据传递给我的sendjs.php。
jsonObj
仅在IE11中未传递(未测试IE的较低版本,但它适用于Edge和所有其他浏览器)。 FormData
和captchaResponse
正在通过。
在'网络'在IE 11检查员中,帖子数据是:
cart: [null]
并且控制台中没有显示错误。
它包含数据的所有其他浏览器:
例如。 cart: {name: "130 Litre Polypropylene Soakwells", price: "$39.95", quantity: "4", total: "$159.80"},…]
此处的实时网站:www.diysoakwells.com.au(您可以添加项目和结帐以进行测试)。
花了很多时间试图找到原因,现在我甚至不确定从哪里开始说实话,所以任何信息都会受到赞赏,我会根据要求更新帖子。
app.js
$(function() {
// Get the form.
var form = $("#ajax-contact");
// Get the messages div.
var formMessages = $("#form-messages");
var spinner = $("#spinner");
var submit = $("#submit");
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//display the cog animation
$(spinner).removeClass("hidden");
//hide the submit button
$(submit).addClass("hidden");
var jsonObj=[];
for(i=1;i<$(".item-price").length;i++)
{
var items={};
var itemname = $(".item-name").get(i);
var itemprice = $(".item-price").get(i);
var itemquantity = $(".item-quantity").get(i);
var itemtotal = $(".item-total").get(i);
items["name"] = itemname.innerHTML;
items["price"] = itemprice.innerHTML;
items["quantity"] = itemquantity.innerHTML;
items["total"] = itemtotal.innerHTML;
jsonObj.push(items);
}
console.log(jsonObj );
var formdata = {};
formdata["textbox"] = $("#textbox").val();
formdata["name"] = $("#name").val();
formdata["phone"] = $("#phone").val();
formdata["email"] = $("#email").val();
formdata["address"] = $("#address").val();
formdata["grandtotal"] = simpleCart.grandTotal();
var x =
{
"cart" : jsonObj,
"formdata" : formdata,
"captchaResponse" : $("#g-recaptcha-response").val()
};
//jsonString = jsonObj+formdata;
var y = JSON.stringify(x);
console.log(y);
var result = jQuery.parseJSON(y);
console.log(result);
// Serialize the form data.
//var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: "post",
url: "sendjs.php" ,
//url: $(form).attr("action"),
data: y,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (response) {
if(response=="Thank You. Your order has been sent and a copy mailed to your inbox.")
{
//remove the button animation
$(spinner).addClass("hidden");
$(formMessages).removeClass("error");
$(formMessages).addClass("success");
$("#textbox").val("");
$("#name").val("");
$("#email").val("");
$("#message").val("");
$("#phone").val("");
$("#address").val("");
}
else
{
$(formMessages).removeClass("success");
$(formMessages).addClass("error");
$(spinner).addClass("hidden");
$(submit).removeClass("hidden");
}
$(formMessages).text(response);
}
});
});
});
sendjs.php
<?php
//Debugging
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
//replaces file_get_contents due to restrictions on server
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//turn url_fopen on due to restrictions on server
//ini_set('allow_url_fopen', true);
date_default_timezone_set('Australia/Perth');
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$captcha = $obj["captchaResponse"];
$captcha;
$secretKey = "scrubbed";
$ip = $_SERVER['REMOTE_ADDR'];
$response = get_data("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
//not used due to server restictions
//$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo "Please Click on the Captcha";
return false;
}
else
{
//echo $items;
$name = $obj["formdata"]["name"];
$phone = $obj["formdata"]["phone"];
$email = $obj["formdata"]["email"];
$textbox = $obj["formdata"]["textbox"];
$address = $obj["formdata"]["address"];
$grandtotal = $obj["formdata"]["grandtotal"];
$text = "<html style='font-family:arial'>
<body>
<h1 style='color:crimson;'>DIY Soakwells</h1>
<p>This order was submitted from www.diysoakwells.com.au on $date at $time</p>
<p>$name thank you for your order inquiry. Deliveries are normally every Friday, we will be in contact shortly to discuss your order and confirm a time.</p>
<p>An invoice will be issued after delivery for payment via bank transfer.</p>
<p>In the meantime if you haven't already seen it, you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate.</p>
<br>
<h2 style='color:crimson;'>CUSTOMER DETAILS</h2>
<p><b>Email:</b>\n$email</p>
<p><b>Name:</b>\n$name</p>
<p><b>Phone:</b>\n$phone</p>
<p><b>Delivery Address:</b>\n$address</p>
<p><b>Message:</b>\n$textbox</p>
<br>
<h2 style='color:crimson;'>ORDER DETAILS</h2>";
$items_in_cart = count($obj["cart"]);
for($i=0; $i < $items_in_cart; $i++) {
$iname = $obj["cart"][$i]["name"];
$price = $obj["cart"][$i]["price"];
$quantity = $obj["cart"][$i]["quantity"];
$total = $obj["cart"][$i]["total"];
//display looped cart data
$items .= "<p>$iname x $quantity - $price <small>ea.</small> <b>Sub Total: </b> $total .</p>";
}
$final_total ="<br>
<p><b>Total: </b>$$grandtotal <small>inc. GST</small></p>
</body>
</html>";
//Email Content
$body = $text.$items.$final_total;
// Set the email subject.
$subject = "New order from $name";
// Build the email content.
$email_content = $body;
// Build the email headers.
$email_headers = 'MIME-Version: 1.0' . PHP_EOL;
$email_headers .= 'Content-Type: text/html; charset=ISO-8859-1' . PHP_EOL;
//$email_headers .= 'To:' . $name . '<' . $email . '>' . PHP_EOL;
$email_headers .= 'From: DIY Soakwells <orders@diysoakwells.com>' . PHP_EOL;
$email_headers .= 'CC: orders@diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'Reply-To: DIY Soakwells <orders@diysoakwells.com.au>' . PHP_EOL;
$email_headers .= 'Return-Path: DIY Soakwells <orders@diysoakwells.com>' . PHP_EOL;
$email_headers .= 'X-Sender: DIY Soakwells <orders@diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
//$email_headers .= 'X-Priority: 1' . PHP_EOL;
//validate Email
$email_check = filter_input(INPUT_POST, $email, FILTER_VALIDATE_EMAIL);
//Recipients
$to = $email;
if (mail($to, $subject, $email_content, $email_headers, '-forders@diysoakwells.com.au')) {
// Set a 200 (okay) response code.
//http_response_code(200);
echo "Thank You. Your order has been sent and a copy mailed to your inbox.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
echo "There appears to be an issue with our server, please ring 0420 903 950 or email contact@diysoakwells.com.au.";
}
}
?>
希望有人能给我一些提示。
编辑:添加购物车模式html
<!-- cart modal panel -->
<section class="modal fade cartModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<!-- Modal Header-->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title cart_summary">
<b>Cart Summary</b>
</h3>
</div>
<!-- Cart Modal Body -->
<section class="modal-body">
<div class="checkout">
<!-- Cart Items -->
<div class="simpleCart_items"></div>
<!-- Cart Items Footer -->
<div class="panel-footer">
<div class="row">
<div class="col-xs-12 col-sm-4 cart_modal_btn">
<a class="btn btn-default btn-sm" onclick="simpleCart.empty();">Clear Cart</a>
</div>
<div class="col-xs-12 col-sm-8 cart_footer_text">
<span class="total">Current Total:
<b class="simpleCart_grandTotal"></b>
<small class=gst>Inc. GST</small>
</span>
</div>
</div>
</div>
</div>
<div>
<h3 class="cart_summary">
<b>Checkout</b>
</h3>
</div>
<!-- Customer Details Form -->
<section class="details_form">
<b class="invoice_info">Due to the custom nature of this service we do not take payment until your order is confirmed and the materials are delivered.</b>
<b class="invoice_info">You will be emailed an invoice with our account details. Payment terms are 5 days from the invoice date please.</b>
<p class="invoice_info">For payment we accept bank transfer and VISA / Master Card <small>(2.3% surcharge for credit cards).</small></p>
<form id="ajax-contact" class="contact_form" method="post">
<fieldset>
<h4 class="contact_form_title">Questions / Additional Information</h4>
<div class="textbox_container">
<textarea rows="5" style="overflow-y:hidden" class="textbox" name="textbox" id="textbox"></textarea>
</div>
<h4 class="contact_form_title">Customer Details</h4>
<table>
<tr>
<th><label for="name" class="cart_label">Enter Name</label></th>
<td><input type="text" name="name" placeholder="Name Required" class="input" id="name" required /></td>
</tr>
<tr>
<th><label for="phone" class="cart_label">Enter Phone Number</label></th>
<td><input type="tel" placeholder="Phone Number Required" name="phone" class="input" id="phone" required/></td>
</tr>
<tr>
<th><label for="emaile" class="cart_label">Enter Email</label></th>
<td><input type="email" placeholder="Email Required" name="emaile" class="input" id="emaile" required/></td>
</tr>
<tr>
<th><label for="address" class="cart_label">Enter Address</label></th>
<td><input type="text" name="address" placeholder="Address / Suburb" class="input" id="address" required/></td>
</tr>
</table>
</fieldset>
<!-- captcha -->
<div class="captcha_container">
<div class="g-recaptcha" data-sitekey="6LfPjyMTAAAAANe_qucSV5ZFAuDNO4Ud524-NGoa" data-size="compact"></div>
</div>
<section class="fb_container">
<div class="fb-like" data-href="http://www.facebook.com/DiySoakwells" data-layout="button_count" data-width="225" data-action="like" data-show-faces="false" data-share="true"></div>
</section>
<br/><!-- css this -->
<fieldset class="submit">
<div class="formMessages submit_field"></div>
<div id="spinner" class="hidden success submit_field"><i class="loader2"></i></div>
<input id="submit" type="submit" name="Submit" value="Send" style="cursor:pointer" class="success"/>
</fieldset>
</form>
</section>
</section>
<!-- Modal Footer-->
<section class="modal-footer">
<button type="button" class="btn btn-default close" aria-label="Close" data-dismiss="modal">Back to Shop</button>
</section>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</section><!-- /.main section -->
简单购物车配置
simpleCart({
//Setting the Cart Columns for the sidebar cart display.
cartColumns: [
//{ attr: "image", label: false, view: "image"},
//Name of the item
{ attr: "name" , label: "Item" },
//Quantity displayed as an input
{ attr: "quantity", label: "Qty", view: "input"},
//Price of item
//{ attr: "price", label: "Price", view: "currency"},
//Subtotal of that row (quantity of that item * the price)
{ attr: "total" , label: "SubTot", view: "currency" }
],
cartStyle: "table" ,
checkout: {
type: "SendForm" ,
url: "/php/sendjs.php" ,
method: "POST" ,
}
});
simpleCart.bind( 'beforeCheckout' , function( data ){
data.name = document.getElementById("name").value;
data.textbox = document.getElementById("textbox").value;
data.emaile = document.getElementById("emaile").value;
data.phone = document.getElementById("phone").value;
data.address = document.getElementById("address").value;
});
Codepen链接到simplecart.js
答案 0 :(得分:6)
更新2
此处的代码使用的是items
,而不是item
,这对我来说很合适。我检查了您使用item
的实际网站,发现代码不工作,它显示您描述的问题。我在本地复制了那些实时破坏的代码,并且能够解决问题,如下所述。
<强>更新强>
我偶然发现了解决方案(如下所述),却没有理解它。经过更多的研究,我现在找到了问题的原因:item
is defined as a native function in IE。
我如何偶然发现答案
我在本地复制了您的代码并使用它。我注意到jsonObj
创建好了,虽然内容看起来很奇怪。同样x
已创建,但在JSON.stringify
之后您的购物车内容已丢失。
console.dir(jsonObj)
显示它是一个对象数组,但每个对象都显示为一个名为item
的函数 - 仅在IE11中:
在Chrome中,它是一组普通对象。
该函数的名称(item
)似乎很奇怪,因为它是您存储购物车项目的对象的名称。函数上的JSON.stringify
将返回null
- 这样可以解释它。
再次检查您的代码我注意到您没有在任何地方声明item
。我试着添加:
var item;
在for (i=1...)
循环之外,这为我解决了!购物车内容不会被JSON.stringify
丢失,devtools会显示购物车,并且您的其他数据已成功发布。
也许item
在其他地方(在SimpleCart中?)作为一个函数声明了,这会妨碍它? UPDATE 是的,这正是发生的事情,虽然它是由浏览器本身声明的,而不是在任何JS中声明。