【问题标题】:Send form data with ajax to a REST CodeIgniter web service from a Phonegap mobile app使用 ajax 将表单数据从 Phonegap 移动应用程序发送到 REST CodeIgniter Web 服务
【发布时间】:2014-12-10 17:17:24
【问题描述】:

我正在编写一个 phonegap 移动应用程序,我想将数据从我的 html 表单发送到我的 codeigniter Web 服务,但它不起作用。 这是我的表单代码:

<form method="POST" action="" id="myform1">
    <input type="text"  id="descr" name="description" placeholder="Légende..">
    <select id="select_file" name="select_file">
        <option value="video">Vidéo</option>
        <option value="son">Son</option>
        <option value="image">Image</option>
        <option value="autre">Autre</option>
    </select>
    <input type="file" id="myfile" name="my_file"/>
    <button type="submit" id="publierFile" >Publier </button>
</form>

我的 ajax 函数:

$('#myform1').submit(function(event) {
    event.preventDefault();
    $.post("mysite-url/webservices/mycontroller/addTest", $('form#myform1').serialize(), function(data) {
        alert("hello");
        console.log(data);
    });

});

还有我的php函数:

public function addTest_post() {
    $desc = $this->post('description');
    $this->response(array("description" => $desc), 201);
}

感谢您的帮助。

【问题讨论】:

  • 在你的 .submit 函数中添加事件。$('#myform1').submit(function(event){
  • 已编辑。错误仍然存​​在。
  • 我认为您面临跨域请求的问题。请参阅此链接。可能会解决您与跨域请求相关的问题。链接在这里“stackoverflow.com/questions/20035101/…
  • 我通过将jsonpattribute 添加到$.post(); 解决了跨域问题
  • 它工作正常吗?

标签: php ajax web-services codeigniter cordova


【解决方案1】:

您需要进行以下更改,同时检查您的控制台是否有错误:

1. $('#myform1').submit(function(event){  //add event in the arguments as you are using 'event.preventDefault();'

2. public function addTest_post(){        //change your function to post to accept post

【讨论】:

  • 还是不行。当我使用 chrome 的调试器时,我得到了这个策略错误,虽然我过去可以访问它:XMLHttpRequest cannot load mysite-url/webservices/mycontroller/addTest。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。
【解决方案2】:

请检查 :root-android-project/res/xml 上的 config.xml 文件 添加这一行

示例代码

<widget xmlns     = "http://www.w3.org/ns/widgets"
    id        = "io.cordova.helloCordova"
    version   = "2.0.0">
<name>Android Apps Cordova</name>

<description>
   Android sample application.
</description>

<author  email="chandrawardhana21@gmail.com">
    Zyra-Studio
</author>

<access origin="*"/>

<!-- <content src="http://myserver.co/myapp.html" /> for external pages -->
<content src="index.html" />

或

关于 Access-Control-Allow-Origin 问题,我遇到了同样的错误,并通过将这一行 &lt;?php header('Access-Control-Allow-Origin: *'); ?&gt; 放在项目根目录下的 index.php 中来解决。

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 2017-05-07
    • 2019-12-15
    相关资源
    最近更新 更多