不能通过AJAX发送Javascript变量

时间:2015-09-02 23:51:10

标签: javascript jquery ajax variables

所以在这个脚本中,变量“encrypted”应该通过ajax发送并传递给upload.php,但是我无法做到这一点。让我们说在ajax中我用一个不同的变量替换“encrypted”变量,它可以工作。为什么我不能通过ajax将变量“encrypted”发送到upload.php

<script src="http://cryptojs.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
    var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");

    $(document).ready(function() {
        // variables to be sent to php
        var formData = {
            'encrypted_data': encrypted
        };

        // process the form
        $.ajax({
                type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
                url: 'upload.php', // the url where we want to POST
                data: formData, // our data object
                dataType: 'json', // what type of data do we expect back from the server
                encode: true
            })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data);

                // here we will handle errors and validation messages
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();

    });
</script>

2 个答案:

答案 0 :(得分:1)

你的var encrypted是一个对象,你应该序列化它:

var formData = {
    encrypted_data: JSON.stringify(encrypted)
};

或发送您需要的任何属性:

var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");

alert(encrypted.key);        // 74eb593087a982e2a6f5dded54ecd96d1fd0f3d44a58728cdcd40c55227522223
alert(encrypted.iv);         // 7781157e2629b094f0e3dd48c4d786115
alert(encrypted.salt);       // 7a25f9132ec6a8b34
alert(encrypted.ciphertext); // 73e54154a15d1beeb509d9e12f1e462a0

答案 1 :(得分:-1)

我从来没有使用过CryptoJS所以我只是在这里猜测,但你是否宣布了CryptoJS?它不在您的代码中。文档 - http://cryptojs.altervista.org/api/#AES

var CryptoJS = new Crypt();