jjzjj

javascript - $jsonObj 数据未通过 ajax 传递,仅在 IE(11) 上通过 POST

coder 2024-01-01 原文

我正在尝试使用 ajax 通过 post 将数据传递到我的 sendjs.php。

jsonObj 不仅在 IE11 中被传递(没有测试过较低版本的 IE,但它在 Edge 和所有其他浏览器中工作)。 FormDatacaptchaResponse 正在传递。

在 IE 11 检查器的“网络”中,发布数据是:

cart: [null] 控制台中没有错误显示。

它包含数据的所有其他浏览器:

例如。 购物车:{名称:“130 升聚丙烯 Soakwells”,价格:“39.95 美元”,数量:“4”,总计:“159.80 美元”},...]

实时站点在这里:www.diysoakwells.com.au (您可以添加项目并结帐以进行测试)。

我花了很长时间试图找到原因,老实说,现在我什至不确定从这里去哪里,所以任何信息将不胜感激,我将根据要求用任何信息更新帖子。

应用程序.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);

            }
        });
    });

});

发送js.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">&times;</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: &nbsp;
                        <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;
});

到 simplecart.js 的代码笔链接

Copy of simplecart.js

最佳答案

更新 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 中?)声明为函数,这会妨碍吗? 更新 是的,这正是正在发生的事情,尽管它是由浏览器本身声明的,而不是在任何 JS 中。

关于javascript - $jsonObj 数据未通过 ajax 传递,仅在 IE(11) 上通过 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45992396/

有关javascript - $jsonObj 数据未通过 ajax 传递,仅在 IE(11) 上通过 POST的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  4. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

  5. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  6. ruby-on-rails - rails : How to make a form post to another controller action - 2

    我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak

  7. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  8. ruby-on-rails - Enumerator.new 如何处理已通过的 block ? - 2

    我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m

  9. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

  10. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

随机推荐