我将ajax传递给php,数据类型为JSONP,但在php文件中显示未定义的索引


I am passing an ajax to php with datatype as JSONP,but showing undefined index in php file

点击提交按钮,我正在传递一个变量到sendmail.php。它显示contactname在php中未定义。为什么会这样?

下面是我的代码:

var name = document.getElementById('stream_cotactname').value;  
alert(name);
$.ajax({
    url: "sendmail.php",
    async: false,
    type:"POST",
   data : "cotactname="+name+"file="  + formdata,
   dataType: "jsonp",
    contentType: false,
        processData:false,
          jsonp: "jsoncallback",
    success: function(html){
         alert("Thank you. We will be in touch with you");
    },
    error: function(){
     alert("Thank you. We will be in touch with you");
    }
});

My Php File:

<?php  
$name =$_POST['cotactname'];die("A".$name);  
 ?>

一切都好,谢谢。

现在让我来介绍我的确切代码:

   <script type="text/javascript">
    var formdata = false;
    (function () {
        var input = document.getElementById("uploaded_file");
        formdata = false;
        formdata = new FormData();
        input.addEventListener("change", function (evt) {
        var i = 0, len = this.files.length, img, reader, file;
        for ( ; i < len; i++ ) {
          file = this.files[i];
    if (formdata) {
            formdata.append("uploaded_file[]", file);
           }
              }
            }, false);
          }());
        </script>

如何在php中获得表单数据信息(就像我们做的$_FILES)

如果你不使用跨域调用,那么你可以这样调用ajax:

$.ajax({
    url: "sendmail.php",
    async: false,
    type:"POST",
   data : {cotactname:name},
   dataType: "json",
    contentType: 'application/x-www-form-urlencoded',
    success: function(html){
         alert("Thank you. We will be in touch with you");
    },
    error: function(){
     alert("Thank you. We will be in touch with you");
    }
});

尝试更改数据发送以获取更多https://api.jquery.com/jQuery.ajax/

data : {cotactname:name},

还尝试检查控制台是否有任何错误,在该文件上post ok或尝试使用正确的文件路径

您正在从ajax发送字符串并获取变量的值。

试试这个:

改变
data : "cotactname="+name,

data: {"cotactname" : name},