简体   繁体   中英

Why am I getting array how to get string

If I have textarea with id leavepost and hidden div id display After # I got hidden div and word with # in var name But when I want to sent itvia ajax to sul file it sends array. What is wrong?

$("#leavepost").keypress(function(event) {
    var key = (event.keyCode ? event.keyCode : event.which);
    if (key == 35) {
        $('#display').show();
        $('#leavepost').on('keyup', function() {
            var name = $(this).val().match(/(^|\s)(#[a-z\d-]+)/ig);
            $.ajax({
                type: "POST",
                url: "d/sul.php",
                data: { su: name },
                success: function(sss)
                {
                    $('#display').html(sss);

                }
            });
        }).keyup();
    }
});

Inside sul.php I have:

echo $_POST['su'];
$u = mysqli_real_escape_string($con, $_POST['su']);

error:

Warning: mysqli_real_escape_string() expects parameter 2 to be string, array given

.match() returns an array of matching tests.

// for example:
"xzxzxz".match(/z/gi)    // => [z,z,z]
"xzxzxz".match(/z/gi)[0] // => "z"

Either use .match(/(^|\\s)(#[az\\d-]+)/ig)[0] to get the first match.

or you can .match(/(^|\\s)(#[az\\d-]+)/ig).join(",") to send all the test matches in a string.

// for example
"xzxzxz".match(/z/gi).join(",") // => "z,z,z"
"xzxzxz".match(/z/gi).join("")  // => "zzz"

You use in this code var name = $(this).val().match(/(^|\\s)(#[az\\d-]+)/ig); String.prototype.match() and this method return:

An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.

So you need to work with $_POST['su']; variable in your php code as with array

It is because the JavaScript match function returns an array.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match

You need to extract the name part from that array. console.log(name) will give you the structure of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM