2017-10-13 1 views
0

내 asp.net HttpPost 테스트 신청자가 우편 배달부에서 정상적으로 작동하지만 HTML AJAX 요청에 오류를 반환합니다. http://localhost:52884/api/contact 몸 : 나는 URL을 우체부의 요청을 실행하는 경우asp.net webapi POST는 우편 배달부에서 작동하지만 브라우저에서는 작동하지 않습니다. AJAX 요청

public class myData 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public int Age { get; set; } 
} 

:

내 컨트롤러 :

public class ContactController : ApiController 
{ 
    [HttpPost] 
    public string Post([FromBody] myData m) 
    { 
     return String.Format("Test A"); 
    } 
} 

클래스

{ 
    "FirstName" : "FName", 
    "LastName" : "LName" 
} 

그것은 잘 실행! "테스트 A"

그러나, 나는 HTML 아약스 요청을하려고 할 때 : I 출력을 볼

<html> 

<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
</head> 

<body> 
    <script> 
     $.ajax(
     { 
      url: "http://localhost:52884/api/contact", 
      type: "POST", 
      dataType: 'jsonp', 
      data: { FirstName: "FName", LastName: "LName" }, 
      success: function (result) { 
       alert(result); 
      }, 
      error: function (xhr, status, p3, p4) { 
       console.debug(xhr); 
       var err = "Error " + " " + status + " " + p3; 
       if (xhr.responseText && xhr.responseText[0] == "{") 
        err = JSON.parse(xhr.responseText).message; 
       alert(err); 
      } 
     }); 
    </script> 
</body> 

</html> 

내가 콘솔에서 오류를 참조하십시오

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol 
Loading failed for the <script> with source “http://localhost:52884/api/contact?callback=jQuery112409902197956907268_1507917530625&FirstName=FName&LastName=LName&_=1507917530626”. 
+0

** dataType : 'jsonp'** ** ** dataType : "json"** **으로 변경하십시오. –

+0

jsonp를 사용하고 있지만 코드에 콜백이 없습니다. JSON.stringyfy ({FirstName : "FName", LastName : "LName"})' – Niladri

+0

웹 API 버전을 사용하고 계십니까? 구성 파일에서 json 형식으로 기본 반환 값을 설정 했습니까? – Niladri

답변

1

좋은 밤을! "FNAME"성을 :

const를 데이터 = {FIRSTNAME : 예를 참조

당신은 { "LNAME": "FNAME"성 FIRSTNAME}에 대해, 개체에 JSON.stringfy를 사용할 필요 : "LName"} const jsonData = JSON.stringfy (data);

URL : "http://localhost:52884/api/contact" 유형 : "POST", dataType와 'JSONP', 데이터 : jsonData, // {FIRSTNAME "FNAME"성 "LNAME"}, 성공 : 기능 (결과) { 알림 (결과); },

도와 드리겠습니다.